Mik*_*ike 3 linux shell redhat
我的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...
Run Code Online (Sandbox Code Playgroud)
当我使用非root用户运行上面的脚本时,它会输出消息"This script ..."但它不会从那里退出,它继续使用剩余的脚本.我究竟做错了什么?
注意:我不想使用if条件.
你正在跑步 echo
和exit
在子弹中.退出调用只会留下子shell,这有点无意义.
试试:
#! /bin/sh
if [ $EUID -ne 0 ] ; then
echo "This script must be run as root" 1>&2
exit 1
fi
echo hello
Run Code Online (Sandbox Code Playgroud)
如果由于某种原因你不想要一个if
条件,只需使用:
#! /bin/sh
[ $EUID -ne 0 ] && echo "This script must be run as root" 1>&2 && exit 1
echo hello
Run Code Online (Sandbox Code Playgroud)
注意:no ()
和固定的布尔条件.警告:如果echo
失败,该测试也将无法退出.该if
版本更安全(更易读,更易于维护IMO).