Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何确定shell脚本是否以root权限运行?_Shell_Permissions_Sudo - Fatal编程技术网

如何确定shell脚本是否以root权限运行?

如何确定shell脚本是否以root权限运行?,shell,permissions,sudo,Shell,Permissions,Sudo,我有一个脚本,我想要求它使用su权限运行,但是有趣的脚本命令会在脚本中很晚出现,所以我想先进行一个干净的测试,以确定如果没有su功能,scrip是否会失败 对于bash、sh和/或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: 您可以在脚本开头添加类似的内

我有一个脚本,我想要求它使用su权限运行,但是有趣的脚本命令会在脚本中很晚出现,所以我想先进行一个干净的测试,以确定如果没有su功能,scrip是否会失败

对于bash、sh和/或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/sh

ROOTUID="0"

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

你试过了吗?看起来不错。你为什么不回答这个问题?:-)此代码的可能副本在POSIX shell中不起作用(
/bin/sh
)。
[[
命令和
EUID
变量是bash特有的——POSIX规范中没有定义它们。而且#!/bin/bash几乎总是错误的。如果必须使用bash(这确实不是首选),那么使用/usr/bin/env bash似乎是那些在问题中特别提到bash的人的首选。
#!/bin/sh

ROOTUID="0"

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