开发者

How do I determine if a shell script is running with root permissions?

开发者 https://www.devze.com 2023-03-13 17:39 出处:网络
I\'ve got a script I want to require b开发者_Python百科e run with su privileges, but the interesting scripted command that will fail comes very late in the script, so I\'d like a clean test up front t

I've got a script I want to require b开发者_Python百科e run with su privileges, but the interesting scripted command that will fail comes very late in the script, so I'd like a clean test up front to determine if the scrip will fail without SU capabilities.

What is a good way to do this for bash, sh, and/or csh?


bash/sh:

#!/usr/bin/env bash
# (Use #!/bin/sh for sh)
if [ `id -u` = 0 ] ; then
        echo "I AM ROOT, HEAR ME ROAR"
fi

csh:

#!/bin/csh
if ( `id -u` == "0" ) then
        echo "I AM ROOT, HEAR ME ROAR"
endif


You might add something like that at the beginning of your script:

#!/bin/sh

ROOTUID="0"

if [ "$(id -u)" -ne "$ROOTUID" ] ; then
    echo "This script must be executed with root privileges."
    exit 1
fi
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号