bash执行顺序:alias --> function --> builtin --> program

linux bash的执行顺序如下所示:

 先 alias --> function --> builtin --> program 后 

验证过程:

1,在bash shell中有内置命令 test ,可以通过 type test 查看如下所示:

 test is a shell builtin 

执行 test 时,看不到任何输出,唯一的响应是,新命令提示符被打印了:

$ test
$
$ which test
  /usr/bin/test

2,备份 /usr/bin/test ,将可执行的 hello copy到 /usr/bin/test 

$ /usr/bin/test
  hello, world!

在shell中执行 test :

$ test
$

说明builtin的test执行优先于program的test

原因是builtin命令避免了不必要的fork/execev调用,builtin命令理论上有更高的运行效率。

 

3,alias(别名)

$ alias test="ls -l"
  $ test
  total 9488
  drwxr-xr-x 12 falcon falcon    4096 2008-02-21 23:43 bash-3.2
  -rw-r--r--  1 falcon falcon 2529838 2008-02-21 23:30 bash-3.2.tar.gz

说明:alias比builtin的test执行更优先

4,function(函数)

$ function test { echo "hi, I'm a function"; }
$ test
  total 9488
  drwxr-xr-x 12 falcon falcon    4096 2008-02-21 23:43 bash-3.2
  -rw-r--r--  1 falcon falcon 2529838 2008-02-21 23:30 bash-3.2.tar.gz

说明:function没有alias优先级高

 

把alias去掉(unalias),执行test:

$ unalias test
$ test
hi, I'm a function

说明:function的优先级比builtin的优先级高

在命令之前加上builtin,那么将直接执行builtin命令:

$builtin test

去掉某个function的定义,使用unset:

$ unset test

 

5,type -a/-t

type -a会按照bash解析的顺序依次打印该命令的类型;type -t会给出第一个被解析的命令的类型

$ type -a test
test is a shell builtin
test is /usr/bin/test
$ alias test="ls -l"
$ function test { echo "I'm a function"; }
$ type -a test
test is aliased to `ls -l'
test is a function
test ()
{
    echo "I'm a function"
}
test is a shell builtin
test is /usr/bin/test
$ type -t test
alias

 

6,PATH执行顺序

PATH指定的多个目录下有同名的程序的情况下,执行顺序是怎样的?在/usr/bin/,/bin,/usr/local/sbin这几个目录,通过type -P查看到底那个PATH下的先执行(-P参数强制到PATH下查找,而不管是别名还是内置命令)

$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
$ type -P test
/usr/local/sbin/test
$ rm /usr/local/sbin/test
$ type -P test
/usr/bin/test

type -a也会显示类似的结果:

$ type -a test
test is aliased to `ls -l'
test is a function
test ()
{
    echo "I'm a function"
}
test is a shell builtin
test is /usr/bin/test
test is /bin/test

 

posted @ 2021-02-08 15:21  burlingame  阅读(567)  评论(0编辑  收藏  举报