Add "not" to if statement in shell script

I have the following script that should exist if the user does not exist.

#check if user currently exists on system
if id $User > /dev/null 2>&1
then #user exists no need to exit program echo "blah blah, what a waste of space"
else echo "This user does NOT exists. Please create that user before using this script.\n" exit
fi

My problem is that I would ideally like to place a "not" if that first if statement so that I can trim down my if, else statement. Ideally I would like something like this:

if !(id $User > /dev/null 2>&1)
then echo "This user does NOT exists. Please create that user before using this script.\n" exit
fi

3 Answers

“Not” is spelled !, with no punctuation and a space after it.

if ! id "$user_name" > /dev/null 2>&1
then echo 1>&2 "This user does NOT exists. Please create that user before using this script.\n" exit 1
fi

Your proposal would actually work, but the parentheses create a subshell to run the one command id, which is superfluous.

Other changes:

  • Always put double quotes around variable substitutions: "$user_name"
  • There is already a variable USER, which is the name of the current logged-in user. Variable names are case-sensitive, but humans not so much.
  • Return a value between 1 and 125 to indicate failure in a program.
  • Report errors to standard error (file descriptor 2), not standard output.
1

There is a not operator in shell scripting, and it is !, but you're not using it quite correctly.

Put a space between the ! operator and its operand, and leave out the parentheses. This should work for all POSIX-style shells, including bash and sh/dash.

if ! id $User > /dev/null 2>&1
then echo "This user does NOT exists. Please create that user before using this script.\n" exit
fi

You can use parentheses for grouping if you like, though it is not necessary in this case. A new subshell is created to execute the parenthesized expression. The ! operator should still have a space between it and the ( character. (Spaces around the parentheses themselves is optional.)

if ! (id $User > /dev/null 2>&1)
then echo "This user does NOT exists. Please create that user before using this script.\n" exit
fi

See Gilles's excellent answer, for some good alternatives and style recommendations. (Also, thanks to Gilles for some corrections about the use of parentheses.)

2

Questions like this one get answered in "Advanced Bash-Scripting Guide"
- which is viewable and available for download at

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like