Pos Anda sebenarnya berisi 2 pertanyaan.
-
-eflag menginstruksikan skrip untuk keluar karena kesalahan. Bendera lainnyaJika ada kesalahan maka akan langsung keluar.
-
$?adalah status keluar dari perintah terakhir. Di Linux status keluar dari0berarti perintah berhasil. Status lainnya berarti terjadi kesalahan.
Untuk menerapkan jawaban ini ke skrip Anda:
egrep "^username" /etc/passwd >/dev/null
akan mencari username di /etc/passwd berkas.
-
Jika sudah ketemu maka exit status
$?akan sama dengan0. -
Jika tidak menemukannya, status keluar akan menjadi sesuatu yang lain (bukan
0). Di sini, Anda ingin mengeksekusiecho "doesn't exist"bagian dari kode.
Sayangnya ada kesalahan dalam skrip Anda, dan Anda akan menjalankan kode itu jika pengguna ada - ubah baris menjadi
if [ $? -ne 0 ]
untuk mendapatkan logika yang benar.
Namun jika pengguna tidak ada, egrep akan mengembalikan kode kesalahan, dan karena -e opsi shell akan segera keluar setelah baris itu, jadi Anda tidak akan pernah mencapai bagian kode itu.
Semua sakelar baris perintah bash didokumentasikan dalam man bash .
-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.