我可以在shell脚本中设置断点吗?

yur*_*ios 7 debugging bash shell breakpoints

有没有办法暂停 shell 脚本的执行来检查环境状态或执行随机命令?

yur*_*ios 1

Bash 或 shell 脚本不具备像 Java、Python 等其他编程语言那样的调试功能。

我们可以将echo "VAR_NAME=$VAR_NAME"命令放在要记录变量值的代码中。

另外,更灵活的解决方案是将此代码放在我们要调试的 shell 脚本的开头位置:

function BREAKPOINT() {
  BREAKPOINT_NAME=$1
  echo "Enter breakpoint $BREAKPOINT_NAME"
  set +e
  /bin/bash
  BREAKPOINT_EXIT_CODE=$?
  set -e
  if [[ $BREAKPOINT_EXIT_CODE -eq 0 ]]; then
    echo "Continue after breakpoint $BREAKPOINT_NAME"
  else
    echo "Terminate after breakpoint $BREAKPOINT_NAME"
    exit $BREAKPOINT_EXIT_CODE
  fi
}

export -f BREAKPOINT
Run Code Online (Sandbox Code Playgroud)

然后,在我们需要中断的代码行,我们像这样调用这个函数:

# some shell script here
BREAKPOINT MyBreakPoint
# and some other shell script here
Run Code Online (Sandbox Code Playgroud)

因此,BREAKPOINT 函数将记录一些输出,然后启动/bin/bash,我们可以在其中运行echo我们想要的任何或其他一些 shell 命令。当我们想继续运行 shell 脚本的其余部分(释放断点)时,我们只需要执行exit命令即可。如果我们需要终止脚本执行,我们将运行exit 1命令。