A system administrator needs to create a shell script that checks if the user 'jdoe' exists in the system and, if not, creates the user with a home directory. The script should also verify that the creation was successful. Which of the following script snippets correctly implements this logic?
Trap 1: if grep -q '^jdoe:' /etc/passwd; then echo 'Exists'; else useradd…
useradd without -m does not create home directory.
Trap 2: if ! id 'jdoe' &>/dev/null; then useradd -m 'jdoe'; else echo…
Logic inverted: if user does NOT exist, create; else echo. But no verification of success.
Trap 3: [ -z $(id 'jdoe' 2>/dev/null) ] && useradd -m 'jdoe' && echo…
[ -z ] checks if the output is empty, but the command substitution may not work as expected; also no error handling.
- A
if grep -q '^jdoe:' /etc/passwd; then echo 'Exists'; else useradd 'jdoe' && echo 'Created'; fi
Why wrong: useradd without -m does not create home directory.
- B
if id 'jdoe' &>/dev/null; then echo 'Exists'; else useradd -m 'jdoe' && echo 'Created' || echo 'Failed'; fi
Correctly checks existence, creates with home dir, and verifies.
- C
if ! id 'jdoe' &>/dev/null; then useradd -m 'jdoe'; else echo 'Exists'; fi
Why wrong: Logic inverted: if user does NOT exist, create; else echo. But no verification of success.
- D
[ -z $(id 'jdoe' 2>/dev/null) ] && useradd -m 'jdoe' && echo 'Created'
Why wrong: [ -z ] checks if the output is empty, but the command substitution may not work as expected; also no error handling.