【Bash百宝箱】shell内建命令之builtin、command、caller

本文深入解析了Shell中的三个内置命令:builtin、command和caller的功能及使用场景。通过具体实例展示了如何避免因同名函数覆盖而无法正常调用内置命令的问题,并介绍了caller命令在调试过程中的应用。

1、builtin

在shell中,内建(builtin)命令builtin,格式如下:

builtin shell-builtin [arguments]

builtin命令用以执行shell的内建命令,既然是内建命令,为什么还要以这种方式执行呢?因为shell命令执行时首先从函数开始,如果自定义了一个与内建命令同名的函数,那么就执行这个函数而非真正的内建命令。

下面以shell内建命令umask为例说明:

$ umask
0002
$ umask() { echo "umask function"; }
$ umask
umask function
$ builtin umask
0002
$ unset -f umask
$ umask
0002

2、command

在shell中,内建(builtin)命令command,格式如下:

command [-pVv] command [arg ...]

command命令类似于builtin,也是为了避免调用同名的shell函数,命令包括shell内建命令和环境变量PATH中的命令。选项“-p”指定在默认的环境变量PATH中查找命令路径。选项“-v”和“-V”用于显示命令的描述,后者显示的信息更详细。

下面以命令ps(“/bin/ps”)为例说明:

$ ps
  PID TTY          TIME CMD
 8726 pts/22   00:00:00 ps
10356 pts/22   00:00:00 bash
$ ps() { echo "function ps"; }
$ ps
function ps
$ command ps
  PID TTY          TIME CMD
 9259 pts/22   00:00:00 ps
10356 pts/22   00:00:00 bash
$ unset -f ps
$ ps
  PID TTY          TIME CMD
 9281 pts/22   00:00:00 ps
10356 pts/22   00:00:00 bash

3、caller

在shell中,内建(builtin)命令caller,格式如下:

caller [expr]

caller命令返回当前活动的子程序调用的上下文,即调用堆栈信息,包括shell函数和内建命令source执行的脚本。没有指定expr时,显示当前子程序调用的行号和源文件名。如果expr是一个非负整数,显示当前子程序调用的行号、子程序名和源文件名。caller命令打印出来的堆栈信息在调试程序时是很有帮助的,当前栈帧为0。如果shell没有子程序调用或者expr是一个无效的位置时,call命令返回false。

下面以例子说明caller命令的用法:

$ cat -n test.sh 
     1  #!/bin/bash
     2  
     3  foo()
     4  {
     5      echo "foo called"
     6      caller 
     7  }
     8  
     9  bar()
    10  {
    11      echo "bar called"
    12      caller 0
    13  }
    14  
    15  test1()
    16  {
    17      echo "test1 called"
    18      caller
    19      caller 0
    20      caller 1
    21      caller 2
    22  }
    23  
    24  test2()
    25  {
    26      echo "test2 called"
    27      test1
    28  }
    29  
    30  test3()
    31  {
    32      echo "test3 called"
    33      test2
    34  }
    35  
    36  foo
    37  bar
    38  test3
$ bash test.sh 
foo called
36 test.sh
bar called
37 main test.sh
test3 called
test2 called
test1 called
27 test.sh
27 test2 test.sh
33 test3 test.sh
38 main test.sh
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值