停止处理源文件并继续

Dan*_*nor 4 bash shell coding-style

当编写源于另一个文件的bash时,有时我想跳过处理,如果某些条件为真.现在,我要么:

  1. 将整个子文件包装在嵌套的if语句中
  2. 在嵌套的if语句中包含对源文件的调用

这两种策略都有一些缺点.如果我能用这种代码样式编写脚本会好得多:

main.sh

echo "before"
. other
echo "after"
Run Code Online (Sandbox Code Playgroud)

other.sh

# guard
if true; then
  # !! return to main somehow
fi
if true; then
  # !! return to main somehow
fi

# commands
echo "should never get here"
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点,以便echo "after"main中的行被调用?

dev*_*ull 5

是的,你可以return:

if true; then
  return
fi
Run Code Online (Sandbox Code Playgroud)

引用help return:

return: return [n]

从shell函数返回.

使函数或源脚本以N指定的返回值退出.如果省略N,则返回状态是函数或脚本中执行的最后一个命令的状态.

退出状态:如果shell未执行函数或脚本,则返回N或失败.