【问题标题】:Determine where a UNIX alias is defined确定 UNIX 别名的定义位置
【发布时间】:2026-01-11 01:50:01
【问题描述】:

是否有(某种)可靠的方法来获取命令的“来源”,即使该命令是别名?例如,如果我把它放在我的 .bash_profile

alias lsa="ls -A"

我想从定义lsa 的命令行中知道,这可能吗?我知道which 命令,但这似乎并没有。

【问题讨论】:

  • 你试过type吗?它不显示定义的位置,但会显示定义。
  • @CarlNorum 你真的应该回答这个问题。
  • @kojiro,它并没有真正回答问题,这是关于 where 定义的问题。不过,我认为这将是有用的信息。
  • @CarlNorum which 也适用于别名
  • shell 跟踪定义函数的源文件和行号,但不跟踪别名。 (无论如何,您应该使用函数而不是别名,因为它们更加灵活;对于这个特定的别名,等效函数将是 lsa() { ls -A "$@"; })。

标签: linux bash shell unix


【解决方案1】:

正如 Carl 在他的评论中指出的那样,type 是找出名称是如何定义的正确方法。

mini:~ michael$ alias foo='echo bar'
mini:~ michael$ biz() { echo bar; }
mini:~ michael$ type foo
foo is aliased to `echo bar'
mini:~ michael$ type biz
biz is a function
biz () 
{ 
    echo bar
}
mini:~ michael$ type [[
[[ is a shell keyword
mini:~ michael$ type printf
printf is a shell builtin
mini:~ michael$ type $(type -P printf)
/usr/bin/printf is /usr/bin/printf

【讨论】:

    【解决方案2】:

    虽然typewhich 会告诉您来源,但它们不会在几个步骤中查找。我为此写了一个小程序:origin。一个例子:

    alext@smith:~/projects/origin$ ./origin ll
    'll' is an alias for 'ls' in shell '/bin/bash': 'ls -alF'
    'ls' is an alias for 'ls' in shell '/bin/bash': 'ls --color=auto'
    'ls' found in PATH as '/bin/ls'
    '/bin/ls' is an executable
    alext@smith:~/projects/origin$
    

    【讨论】:

      【解决方案3】:

      此函数将提供有关它是什么类型的命令的信息:

      ft () {
          t="$(type -t "$1")";
          if [ "$t" = "file" ]; then
              if which -s "$1"; then
                  file "$(which "$1")"
              else
                  return 1
              fi
          else
              echo $t
          fi
          return 0
      }
      

      它会吐出builtinalias 等,如果是文件,则会吐出类似/bin/ls: Mach-O 64-bit x86_64 executable 的行,如果不存在则什么都不存在。在最后一种情况下,它将返回错误。

      【讨论】:

      • 你为什么要使用whichtype 也可以进行路径查找——参见 -P 参数。