且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

即使退出命令后,Shell脚本仍继续运行

更新时间:2023-12-05 19:17:58

您正在子壳中运行 echo exit .退出调用只会离开该子Shell,这毫无意义.

You're running echo and exit in subshells. The exit call will only leave that subshell, which is a bit pointless.

尝试:

#! /bin/sh
if [ $EUID -ne 0 ] ; then
    echo "This script must be run as root" 1>&2
    exit 1
fi
echo hello

如果由于某种原因您不希望 if 条件,只需使用:

If for some reason you don't want an if condition, just use:

#! /bin/sh
[ $EUID -ne 0 ] && echo "This script must be run as root" 1>&2 && exit 1
echo hello

注意:没有()和固定的布尔条件.警告:如果 echo 失败,该测试也将无法退出. if 版本更安全(并且更具可读性,更易于维护IMO).

Note: no () and fixed boolean condition. Warning: if echo fails, that test will also fail to exit. The if version is safer (and more readable, easier to maintain IMO).