Sunday, May 5, 2024
 Popular · Latest · Hot · Upcoming
5
rated 0 times [  5] [ 0]  / answers: 1 / hits: 5034  / 2 Years ago, mon, february 21, 2022, 9:43:21

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.
"
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.
"
exit
fi

More From » bash

 Answers
4

“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.
"
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.


[#29447] Tuesday, February 22, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ainsbeave

Total Points: 280
Total Questions: 98
Total Answers: 105

Location: Faroe Islands
Member since Sat, Aug 20, 2022
2 Years ago
;