13

I'm writing a shell script that looks like this:

 for i in $ACTIONS_DIR/*
    do
            if [ -x $i ]; then
                    exec $i nap
            fi
    done

Now, what I'm trying to achieve is to list every file in $ACTIONS_DIR to be able to execute it. Each file under $ACTIONS_DIR is another shell script.

Now, the problem here is that after using exec the script stops and doesn't go to the next file in line. Any ideas why might this be?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
user175259
  • 4,641
  • 5
  • 20
  • 15

3 Answers3

18

exec replaces the shell process. Remove it if you only want to call the command as a subprocess instead.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
8

exec transfers control of the PID over to the program you're exec'ing. This is mainly used in scripts whose sole purpose is to set up options to that program. Once the exec is hit, nothing below it in the script is executed.

Also, you should try some quoting techniques:

for i in "$ACTIONS_DIR"/*
    do
        if [ -x "$i" ]; then
                "./$i" nap
        fi
done

You might also look into using find for this operation:

find "$ACTIONS_DIR" \
    -maxdepth 1 \
    -type f \
    -perm +0111 \
    -exec {} nap \;
amphetamachine
  • 27,620
  • 12
  • 60
  • 72
  • 1
    `for i in "$ACTIONS_DIR"/*` would be a bit safer if we don't know the directory name not to contain whitespace (or if we don't know/control the value of `IFS`). – Charles Duffy Oct 20 '17 at 22:05
2

exec never returns to the caller. Just try

if [ -x "${i}" ]
then
    "${i}" nap
fi
Tripp Kinetics
  • 5,178
  • 2
  • 23
  • 37
Himanshu
  • 1,989
  • 16
  • 12