jam*_*esT 4 shell ksh shell-script exit
我有一个关于 unix shell 脚本的问题。
假设你exit 1在内部执行if:它会退出还是仍然执行外部if?以下是一个虚拟示例。
if [ "$PASSWORD" == "$VALID_PASSWORD" ]; then
if [ "$PASSWORD" -gt 10]; then
echo "password is too large!"
exit 1
fi
echo "You have access!"
exit 1
fi
Run Code Online (Sandbox Code Playgroud)
exit终止调用进程。在大多数情况下,这会退出整个脚本,即使您从循环、函数或包含的脚本内部调用它也是如此。唯一“捕获”的 shell 构造是exit引入子 shell(即分叉子 shell 进程)的那些:
(…)执行子shell中括号内命令的基本子shell构造;$(…)(及其已弃用的等价物,反引号`…`),它执行命令并将其输出作为字符串返回;&;|,和右手侧,以及在大多数壳(ATT KSH和ZSH作为例外);<(…),>(…)等,对KSH,bash和zsh中。您可以使用关键字跳出whileorfor循环break,也可以使用return关键字跳出函数。
exit通常是内置的外壳,因此理论上它确实取决于您使用的外壳。但是,除了退出当前进程之外,我不知道它运行的任何 shell。从 bash 手册页,
exit [n]
Cause the shell to exit with a status of n. If n is omitted,
the exit status is that of the last command executed. A trap on
EXIT is executed before the shell terminates.
Run Code Online (Sandbox Code Playgroud)
所以它不是简单地结束当前if子句,而是退出整个 shell(或进程,本质上,因为脚本是在 shell 进程中运行的)。
来自 man sh,
exit [exitstatus]
Terminate the shell process. If exitstatus is given it is used as
the exit status of the shell; otherwise the exit status of the
preceding command is used.
Run Code Online (Sandbox Code Playgroud)
最后,来自 man ksh,
† exit [ n ]
Causes the shell to exit with the exit status specified by n.
The value will be the least significant 8 bits of the specified
status. If n is omitted, then the exit status is that of the
last command executed. An end-of-file will also cause the shell
to exit except for a shell which has the ignoreeof option (see
set below) turned on.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16981 次 |
| 最近记录: |