即使退出命令后,Shell 脚本仍继续运行
我的 shell 脚本如下所示:
#!/bin/bash
# Make sure only root can run our script
[ $EUID -ne 0 ] && (echo "This script must be run as root" 1>&2) || (exit 1)
# other script continues here...
当我使用非 root 用户运行上述脚本时,它会打印消息“此脚本...”,但它不会在那里退出,它会继续执行剩余的脚本。我做错了什么?
注意:我不想使用 if 条件。
My shell script is as shown below:
#!/bin/bash
# Make sure only root can run our script
[ $EUID -ne 0 ] && (echo "This script must be run as root" 1>&2) || (exit 1)
# other script continues here...
When I run above script with non-root user, it prints message "This script..." but it doe not exit there, it continues with the remaining script. What am I doing wrong?
Note: I don't want to use if condition.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在子 shell 中运行
echo
和exit
。 exit 调用只会留下该子 shell,这有点毫无意义。尝试使用:
如果由于某种原因您不需要
if
条件,只需使用:注意:没有
()
和固定布尔条件。警告:如果echo
失败,该测试也将无法退出。if
版本更安全(并且更具可读性,更易于维护 IMO)。You're running
echo
andexit
in subshells. The exit call will only leave that subshell, which is a bit pointless.Try with:
If for some reason you don't want an
if
condition, just use:Note: no
()
and fixed boolean condition. Warning: ifecho
fails, that test will also fail to exit. Theif
version is safer (and more readable, easier to maintain IMO).我认为您需要
&&
而不是||
,因为您想要 echo 并 退出(而不是 echo 或 退出)。此外,
(exit 1)
将运行一个退出的子 shell,而不是退出当前的 shell。以下脚本显示了您所需要的内容:
使用
./myscript 0
运行此脚本将为您提供:而
./myscript 1
将为您提供:我相信这就是您正在寻找的内容。
I think you need
&&
rather than||
, since you want to echo and exit (not echo or exit).In addition
(exit 1)
will run a sub-shell that exits rather than exiting your current shell.The following script shows what you need:
Running this with
./myscript 0
gives you:while
./myscript 1
gives you:I believe that's what you were looking for.
我将其写为:
使用
{ }
进行分组,该分组在当前 shell 中执行。请注意,大括号周围的空格和结尾的分号是必需的。I would write that as:
Using
{ }
for grouping, which executes in the current shell. Note that the spaces around the braces and the ending semi-colon are required.