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.

Linger
  • 251
  • 3
  • 9
  • 25
Ahmed Laatabi
  • 133
  • 1
  • 5

4 Answers4

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
Zoredache
  • 130,897
  • 41
  • 276
  • 420
  • 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 :) – Ahmed Laatabi Apr 05 '12 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.)

Gordon Davisson
  • 11,216
  • 4
  • 28
  • 33
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
user9517
  • 115,471
  • 20
  • 215
  • 297
  • 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 :) – Ahmed Laatabi Apr 05 '12 at 16:46
1

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

johnshen64
  • 5,865
  • 24
  • 17