linux – 即使在退出命令后,Shell脚本仍继续运行
发布时间:2020-12-14 00:04:10 所属栏目:Linux 来源:网络整理
导读:我的 shell脚本如下所示: #!/bin/bash# Make sure only root can run our script[ $EUID -ne 0 ] (echo "This script must be run as root" 12) || (exit 1)# other script continues here... 当我使用非root用户运行上面的脚本时,它会输出消息“This scrip
我的
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用户运行上面的脚本时,它会输出消息“This script …”但它不会从那里退出,它继续使用剩余的脚本.我究竟做错了什么? 注意:我不想使用if条件. 解决方法
你正在运行echo并退出子shell.退出调用只会留下子shell,这有点无意义.
试试: #! /bin/sh if [ $EUID -ne 0 ] ; then echo "This script must be run as root" 1>&2 exit 1 fi echo hello 如果由于某种原因你不想要if条件,只需使用: #! /bin/sh [ $EUID -ne 0 ] && echo "This script must be run as root" 1>&2 && exit 1 echo hello 注意:no()和固定的布尔条件.警告:如果echo失败,该测试也将无法退出. if版本更安全(更易读,更易于维护IMO). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |