0

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?

1 Answer 1

1

$(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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.