我创建了这个 bash 函数,通过检查执行命令的用户的 uid + 主目录来检测运行的用户是否实际上以 root 用户身份登录,而不是使用 sudo:
#!/bin/bash
set -x
function check_root(){
home=`sh -c 'cd ~/ && pwd'`
if [ "$home" != "/root" ] || [ "$(id -u)" != "0" ]; then
echo -e "This script can only be executed by the root user, not with sudo elevation"
exit 1
fi
}
check_root
当我作为普通用户(uid 1000)运行它时,它按预期工作:
++ check_root
+++ sh -c 'cd ~/ && pwd'
++ home=/home/jake
++ '[' /home/jake '!=' /root ']'
++ echo -e 'This script can only be executed by the root user, not with sudo elevation'
This script can only be executed by the root user, not with sudo elevation
++ exit 1
当我以 root 身份运行它时,它也按预期工作:
++ check_root
+++ sh -c 'cd ~/ && pwd'
++ home=/root
++ '[' /root '!=' /root ']'
+++ id -u
++ '[' 0 '!=' 0 ']'
但是当我以普通用户(uid 1000)身份使用 sudo 提升运行它时,我得到:
./check_root.sh: 4: ./check_root.sh: Syntax error: "(" unexpected
系统信息:
Linux jake 3.11.0-26-generic #45~precise1-Ubuntu SMP 7 月 15 日星期二 04:02:35 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
bash --版本 GNU bash,版本 4.2.25(1)-release (x86_64-pc-linux-gnu)
答案1
我同时解决了这个问题,但尚未发布解决方案 - 结果与语法相关:
工作解决方案:
function check_root {
stuff..
}
和
function check_root () {
stuff..
}
例如,从函数声明中删除 () 或确保其两侧用空格分隔即可修复此问题。
这是我在 bash 联机帮助页中发现的内容,使我发现了错误:
Shell Function Definitions
A shell function is an object that is called like a simple command and executes a compound command with a new set of positional parameters. Shell functions are declared as follows:
name () compound-command [redirection]
function name [()] compound-command [redirection]
This defines a function named name. The reserved word function is optional. If the function reserved word is supplied, the parentheses are optional
但是..我不知道在这种情况下到底是什么让 bash 表现得如此。