Linux – bash : “set -e” and check if a user exists make script exit

bashgreplinuxscriptingshell

I am writing a script to install a program with Bash. I want to exit on error so I added set -e to the beginning of my script.

I have to check if a user exists inside of my script. To do this I am using grep ^${USER}: /etc/passwd. If the user exists, the script runs normally. However, if the user doesn't exist, this command exits. I don't want to exit should the latter case occur. Instead, I want to create the user and continue my installation.

What's the solution to make my script continue running? I tried to redirect the output of grep to a variable, but I still have the same problem.

Best Answer

You could always do something like below. Basically disabling the exit checking around the command you are running.

#!/bin/bash
set -e # eanble exit checking
lorem ipsum 
dolor sit amet
# temp disable exit checking
set +e
grep "^${USER}:" /etc/passwd
set -e
consectetur adipiscing elit
Related Topic