Search code examples
shellexitstatus

shell script: incorrect exit status of executed command


I'd like to get exit status of the command passed as argument (to my sh script called a.sh).

I've tried:

#!/bin/sh

CMD="$@"

echo "arg passed CMD: $CMD"
($CMD) >/dev/null 2>&1
res=$?
echo "exit status: $res"


CMD="echo aaa | grep -q zzz"

echo "in script CMD: $CMD"
($CMD) >/dev/null 2>&1
res=$?
echo "exit status: $res"

Once executing:

./a.sh 'echo aa | grep -q zzz'
arg passed CMD: echo aa | grep -q zzz
exit status: 0
in script CMD: echo aaa | grep -q zzz
exit status: 0

However if I run the command directly in shell I see:

 /bin/sh -c 'echo aa | grep -q zzz ; echo $?'
 1

How should my script look like, to get the correct status 1 instead of 0 of the executed command?


Solution

  • $(CMD) output were aaa | grep -q zzz that is why it return with exit 0. Just remove the redirection to /dev/null and you will see. You could use eval to run commands from variables.

    #!/bin/sh
    
    CMD="$@"
    
    echo "arg passed CMD: $CMD"
    eval $CMD >/dev/null 2>&1
    res=$?
    echo "exit status: $res"
    
    CMD="echo aaa | grep -q zzz"
    
    echo "in script CMD: $CMD"
    eval $CMD >/dev/null 2>&1
    res=$?
    echo "exit status: $res"