
Ich habe diese Bash-Funktion erstellt, um festzustellen, ob der ausgeführte Benutzer tatsächlich als Root-Benutzer angemeldet ist und nicht sudo verwendet, indem ich die UID und das Home-Verzeichnis des Benutzers überprüfe, der den Befehl ausführt:
#!/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
Wenn ich es als normaler Benutzer (UID 1000) ausführe, funktioniert es wie erwartet:
++ 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
Wenn ich es als Root ausführe, funktioniert es auch wie erwartet:
++ check_root
+++ sh -c 'cd ~/ && pwd'
++ home=/root
++ '[' /root '!=' /root ']'
+++ id -u
++ '[' 0 '!=' 0 ']'
Aber wenn ich es als normaler Benutzer (UID 1000) mit Sudo-Elevation ausführe, erhalte ich Folgendes:
./check_root.sh: 4: ./check_root.sh: Syntax error: "(" unexpected
Systeminformationen:
Linux jake 3.11.0-26-generic #45~precise1-Ubuntu SMP Dienstag, 15. Juli 2014, 04:02:35 UTC x86_64 x86_64 x86_64 GNU/Linux
bash --version GNU bash, Version 4.2.25(1)-release (x86_64-pc-linux-gnu)
Antwort1
Ich habe das Problem inzwischen gelöst, aber die Lösung noch nicht gepostet – es stellte sich heraus, dass es mit der Syntax zusammenhängt:
Funktionierende Lösungen:
function check_root {
stuff..
}
Und
function check_root () {
stuff..
}
Das Problem lässt sich beispielsweise beheben, indem man () aus der Funktionsdeklaration entfernt oder sicherstellt, dass es auf beiden Seiten durch Leerzeichen getrennt ist.
Folgendes habe ich in der Bash-Manpage gefunden, wodurch ich den Fehler entdeckt habe:
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
Aber ... ich habe keine Ahnung, warum sich Bash in diesem Fall genau so verhält.