help caller
caller: caller [表达式]
    返回当前子调用的上下文。

    不带有 EXPR 时,返回 "$line $filename"。带有 EXPR 时,返回
    "$line $subroutine $filename";这个额外的信息可以被用于提供
    栈追踪。

    EXPR 的值 显示了到当前调用帧需要回去多少个调用帧;顶部帧
    是第 0 帧。

    退出状态:
    除非 shell 不在执行一个 shell 函数或者 EXPR 无效,否则返回结
    果为0。

只找到一个链接

http://wiki.bash-hackers.org/commands/builtin/caller

测试脚本callertest.sh的内容为

#!/bin/bash

die() {
  local frame=0
  while caller $frame; do
    ((frame++));
  done
  echo "$*"
  exit 1
}

f1() { die "*** an error occured ***"; }
f2() { f1; }
f3() { f2; }

f3

要使用

bash callertest.sh

而不可以用

sh callertest.sh

执行结果为:

12 f1 callertest.sh
13 f2 callertest.sh
14 f3 callertest.sh
16 main callertest.sh
*** an error occured ***

这是不带有EXPR,即表达式的情况,打印

$line $subroutine $filename

分别为

行数 子程序 文件名

EXPR作为可选项,当你设定数字n时,调用其第n帧,但是在上面的这个脚本修改如下:

#!/bin/bash

die() {
  local frame=0
  while caller 2  $frame; do  #2换为0、1、3都会死循环,0为第一帧,也就是输出的第一句。4或者以上只会跳转为最后一句输出。
   ((frame++));
  done
  echo "$*"
  exit 1
}

f1() { die "*** an error occured ***"; }
f2() { f1; }
f3() { f2; }

f3

这个命令不是很常用啊!

results matching ""

    No results matching ""