bash 脚本中的 exit 0、exit 1 和 exit 2 是什么意思?

and*_*čič 82 bash scripts

我正在做一些练习练习。

编写一个脚本,该脚本将给出一个月份数字作为参数,并将该数字转换为月份名称。结果将打印到标准输出。

我做了一个解决方案:

# Test for number of argument

if [ "$#" -eq 0 ] ; 
then
  echo -e "No argument."
  echo -e "Write a number between 1 and 12."
  exit 1
elif [ "$#" -gt 1 ] ;
then
  echo -e "More than 1 argument."
  echo -e "Write a number between 1 and 12."
  exit 1
else
  numb=$1
  case "$numb" in
    1) echo "Month: January";;
    2) echo "Month: February";;
    3) echo "Month: March";;
    4) echo "Month: April";;
    5) echo "Month: May";;
    6) echo "Month: June";;
    7) echo "Month: July";;
    8) echo "Month: August";;
    9) echo "Month: September";;
   10) echo "Month: October";;
   11) echo "Month: November";;
   12) echo "Month: December";;
    *) echo -e "You wrote a wrong number. Try again with writing number between 1 and 12.";;
  esac
fi
exit 2
exit 0
Run Code Online (Sandbox Code Playgroud)

做什么exit 1, exit 0exit 2意味着,我们为什么要使用它?

use*_*733 100

这是shell 退出代码的一个很好的参考

Exit code 0        Success
Exit code 1        General errors, Miscellaneous errors, such as "divide by zero" and other impermissible operations
Exit code 2        Misuse of shell builtins (according to Bash documentation)        Example: empty_function() {}
Run Code Online (Sandbox Code Playgroud)

警告:使用正确的退出代码不是必需的,也不是由 shell 强制执行的。如果开发人员认为明智,他们可以忽略该指南。

  • 不过要小心。退出代码的含义完全取决于程序的开发人员。 (14认同)

Arr*_*cal 24

使用exit和 数字是表示脚本结果的一种方便方式。它模仿 bash 命令输出返回码的方式。对于 bash 命令,返回码 0 通常意味着一切都成功执行而没有错误。exit还使您的脚本在该点停止执行并返回到命令行。

任何大于 0 的返回码都表示某种错误,尽管有时错误并不严重,但对于每个命令,应该可以找到一些文档来告诉您每个返回码的含义。

您可以通过使用 shell 变量来获取最后一个 bash 命令的返回码,$?如下所示:

$ echo "something"
something
$ echo $?
0
$ cp
cp: missing file operand
Try 'cp --help' for more information.
$ echo $?
1
Run Code Online (Sandbox Code Playgroud)

当您在脚本中使用它时,您可以在执行完成后以相同的方式查询返回码。所以你会看到:

exit 2
exit 0
Run Code Online (Sandbox Code Playgroud)

有点无意义,因为您永远无法到达该exit 0部分。


小智 5

就其本身而言,exit意味着退出值为零,或成功完成您的脚本。您不必向 exit 命令添加零参数来指示成功完成。您的脚本可能(或可能会)成功退出,尽管它会测试错误条件。在这种情况下,您特别希望它以错误(或 1)条件退出。

echo -e "Enter numbers 1-4" \c"
read NUM
case $NUM in 
    1) echo "one";;
    2) echo "two";;
    3) echo "three";;
    4) echo "four";;
    *) echo "invalid answer"
       exit 1;;
esac
Run Code Online (Sandbox Code Playgroud)

exit最后一行中的命令根本不必在那里。它可以用零调用或根本不调用。如果不为 exit 命令指定 1 参数,则所有这些情况下的答案都echo $?将为零。

但是,通过为 exit 命令指定 1 参数,对 的响应echo $?将为 1。因此,当您想指定脚本已退出并出现错误情况时,请使用 1 参数到 exit 命令。