【问题标题】:Exiting a shell script with an error退出带有错误的 shell 脚本
【发布时间】:2015-11-30 22:44:33
【问题描述】:

基本上我已经为家庭作业编写了一个运行良好的 shell 脚本,但是我在退出时遇到了问题。本质上,脚本从用户那里读取数字,直到它读取一个负数,然后进行一些输出。我将脚本设置为在收到除数字以外的任何内容时退出并输出错误代码,这就是问题所在。

代码如下:

if test $number -eq $number >dev/null 2>&1
then
   "do stuff"
else
    echo "There was an error"
    exit

问题是我们必须使用脚本将程序作为文本文件提交,每当我尝试编写程序脚本并测试错误情况时,它也会退出脚本。有一个更好的方法吗? 该脚本正在终端中使用以下命令运行

script "insert name of program here"

谢谢

【问题讨论】:

  • 如何运行脚本?
  • @JerryJeremiah,鉴于 OP 似乎根本不知道他们是在调用还是在采购,我不确定这可能是重复的,直到他们被告知可以选择一个. :)
  • 旁白:请参阅shellcheck.net,以便在您在这里提问之前自动检测到易于捕获的错误。
  • 另外,您的script "insert name of program here" 也不是很有帮助。在这种情况下,script 是外部script 命令吗?是外部测试脚本吗,insert name of program here 是被测内部脚本的名称?如果是这样,测试脚本如何调用被测程序?

标签: shell


【解决方案1】:

如果您正在测试的程序作为子进程 调用,那么任何exit 命令都只会退出命令本身。您看到相反的行为这一事实意味着您必须以不同的方式调用它。


从父测试程序调用脚本时,使用:

# this runs "yourscript" as its own, external process.
./yourscript

...将其作为子进程调用,而不是

# this is POSIX-compliant syntax to run the commands in "yourscript" in the current shell.
. yourscript

...或...

# this is bash-extended syntax to run the commands in "yourscript" in the current shell.
source yourscript

...因为后者将运行所有命令——包括exit——在你当前的shell中,修改它的状态,或者在exitexec或类似的情况下,告诉它停止执行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多