3

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.

4 Answers 4

7

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 
1
  • yes, it's working :) thanks so much, i didn't know that i can disable "set -e" at any place, thanks again Zoredache, problem solved :) Commented Apr 5, 2012 at 16:46
6

In addition to the suggestions already given, here are two more choices. First, you can provide an alternate command that'll guarantee success:

grep "^${USER}:" /etc/passwd || true 

(Basically, if the grep command fails, this'll run true and since that always succeeds it'll consider the compound command to have succeeded and won't exit the script.)

Alternately, since your interest is whether the grep succeeds (i.e. whether you need to add the user), just use it as the condition in an if statement:

if ! grep "^${USER}:" /etc/passwd; then # Create the user account fi # Continue installation... 

(Note that the ! before the grep command negates the test, so it runs the body of the if statement only if grep fails. Since grep is part of a compound command, the script doesn't exit if it fails.)

1
  • excellent idea, thanks for this informations, it's working too :) Commented Apr 6, 2012 at 9:53
4

The solution is to not use set -e which can be quite dangerous. Use if statements where appropriate instead.

grep "^${USER}:" /etc/passwd &>/dev/null if [ $? -eq 1 ] then #create user here ... ft 
1
  • no i can't, i am installing a program with (configure, make, ...), so i have to exit if there's an error at this level. thanks anyway, problem solved, see next answer :) Commented Apr 5, 2012 at 16:46
1

one suggestion is to run that check and install in a subshell within (). would that work for you?

1
  • This is the best way, in my opinion Commented Apr 8, 2012 at 5:11

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.