Create user if UID not exist; else, exit the script

Hi, I want to write a script to check whether an user ID is used in my server and then create that user.

If the user ID is not used, I will echo something like "OK, continue" and then continue to execute the script. Else, I will echo something like "Used, exit" and then exit the script.

As my system only have around 10 users, using grep and awk the /etc/passwd, I can check whether the UID is used. But in the shell script, when I want to
cat /etc/passwd | grep 'UID' | awk $3 and save the result to a variable, I can't do so.

Do anyone have idea on how can I write this shell script? I have no idea now since I can't save the "cat /etc/passwd" to a variable.

You could use the id command:

# cat myScript
if ! id 2340 > /dev/null 2>&1; then
  echo ok to create user...
fi

# ./myScript
ok to create user...

what you mean by cant save to variable ?

UID is the variable which has the user id.

 
RESULT=$(awk -F: -v U="$UID" '$3==U {print "yes";exit}' /etc/passwd)
 
[ -z $RESULT ] && echo "Already Exists..Exiting..." && exit 1
#else your code goes here...
.....
.....

I think you forgot something important for your awk :wink:

1 Like

filenaming is mising.. thanks scott.. its corrected now.