bash:如果root没有运行脚本,则会失败

fly*_*ire 14 linux bash

我有一个安装一些软件的bash脚本.如果它不是由root运行的话我想尽快失败.我怎样才能做到这一点?

Dav*_*own 28

#!/bin/bash
if [ "$(id -u)" != "0" ]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi
Run Code Online (Sandbox Code Playgroud)

资料来源:http://www.cyberciti.biz/tips/shell-root-user-check-script.html


Tom*_*Tom 8

在深入研究之后,共识似乎是不需要id -u在bash中使用,因为将设置EUID(有效用户id)变量.相反UID,EUID将是0用户root使用或使用时sudo.显然,这比跑步快100倍id -u:

#!/bin/bash
if (( EUID != 0 )); then
    echo "You must be root to do this." 1>&2
    exit 1
fi
Run Code Online (Sandbox Code Playgroud)

资料来源:https://askubuntu.com/questions/30148/how-can-i-determine-whether-a-shellscript-runs-as-root-or-not

  • 但这在Bourne shell中不起作用.你有严格的POSIX兼容解决方案吗? (2认同)