Ihr Beitrag enthält eigentlich 2 Fragen.
-
Der
-eflag weist das Skript an, bei einem Fehler zu beenden. Mehr FlaggenWenn ein Fehler auftritt, wird es sofort beendet.
-
Die
$?ist der Exit-Status des letzten Befehls. Unter Linux ein Exit-Status von0bedeutet, dass der Befehl erfolgreich war. Jeder andere Status würde bedeuten, dass ein Fehler aufgetreten ist.
So wenden Sie diese Antworten auf Ihr Skript an:
egrep "^username" /etc/passwd >/dev/null
würde nach username suchen im /etc/passwd Datei.
-
Wenn es ihn findet, dann der Exit-Status
$?entspricht0. -
Wenn es ihn nicht findet, ist der Exit-Status etwas anderes (nicht
0). Hier möchten Sieecho "doesn't exist"ausführen Teil des Codes.
Leider Es gibt einen Fehler in Ihrem Skript und Sie würden diesen Code ausführen, wenn der Benutzer existiert - Ändern Sie die Zeile in
if [ $? -ne 0 ]
um die Logik richtig hinzubekommen.
Allerdings wenn der Benutzer nicht existiert, egrep wird einen Fehlercode zurückgeben, und aufgrund der -e Option wird die Shell sofort nach dieser Zeile beendet, sodass Sie diesen Teil des Codes nie erreichen würden.
Alle Bash-Befehlszeilenschalter sind in man bash dokumentiert .
-e Exit immediately if a pipeline (which may consist of a
single simple command), a subshell command enclosed in
parentheses, or one of the commands executed as part of
a command list enclosed by braces (see SHELL GRAMMAR
above) exits with a non-zero status. The shell does not
exit if the command that fails is part of the command
list immediately following a while or until keyword,
part of the test following the if or elif reserved
words, part of any command executed in a && or || list
except the command following the final && or ||, any
command in a pipeline but the last, or if the command's
return value is being inverted with !. A trap on ERR,
if set, is executed before the shell exits. This option
applies to the shell environment and each subshell envi-
ronment separately (see COMMAND EXECUTION ENVIRONMENT
above), and may cause subshells to exit before executing
all the commands in the subshell.