在获取脚本时,如何在不退出调用 shell 的情况下跳过脚本的其余部分?

Tim*_*Tim 8 bash shell-script exit source-command

我有一个 bash 脚本,exitgetopts无法识别选项或找不到预期的选项参数时,我会在某个地方调用以跳过脚本的其余部分。

while getopts ":t:" opt; do
    case $opt in
        t)
            timelen="$OPTARG"
            ;;
        \?) printf "illegal option: -%s\n" "$OPTARG" >&2
            echo "$usage" >&2
            exit 1
            ;;
        :) printf "missing argument for -%s\n" "$OPTARG" >&2
           echo "$usage" >&2
           exit 1
           ;;
    esac
done

# reset of the script
Run Code Online (Sandbox Code Playgroud)

source在 bash shell 中编写脚本。当出现问题时,shell 会退出。

除了exit跳过脚本的其余部分但不退出调用外壳之外,还有其他方法吗?

替换exitwithreturn不像函数调用那样工作,脚本的其余部分将运行。

谢谢。

ImH*_*ere 8

使用return.

return bash 内置将退出源脚本而不停止调用(父/源)脚本。

从人bash:

return [n]
使函数停止执行并将 n 指定的值返回给其调用者。如果省略 n,则返回状态为函数体中执行的最后一个命令的状态。…如果 return 在函数外使用,但在脚本执行期间由 . (source) 命令,它会导致 shell 停止执行该脚本并返回 n 或脚本中执行的最后一个命令的退出状态作为脚本的退出状态。


Joh*_*oon 6

您可以简单地将脚本包装在函数中,然后使用return您描述的方式。

#!/bin/bash
main () {
    # Start of script
    if [ <condition> ]; then
        return
    fi
    # Rest of the script will not run if returned
}

main "$@"
Run Code Online (Sandbox Code Playgroud)