0

I have a command that is constructed within a variable in a bash script, like so:

CMD="cowsay "
CMD+="-n "
CMD+="foo-moo"

I want to run this command, then exit the script with the return value of the command. I can do:

${CMD}
exit $?

But is there some way of doing this as a single action (i.e. without using $? or similar)? I tried variations on the following but could not achieve the desired result myself.

exit "$(${CMD})"
6
  • 1
    Boy! Linefeeds must be really expensive in your part of the world ;-) Commented Sep 27, 2018 at 11:11
  • Your approach is trying to exit using the text output from your command. Commented Sep 27, 2018 at 11:12
  • @GemTaylor Yes - this is why I mentioned that it doesn't work. Commented Sep 27, 2018 at 11:15
  • @MarkSetchell Heh, really I don't like to use this way in case the two statements get split up, for example by an echo "Command finished" or something Commented Sep 27, 2018 at 11:16
  • result=$? followed by echo "Command finished" then exit $result maybe? Commented Sep 27, 2018 at 11:19

1 Answer 1

1

Try

exec ${CMD}

That will replace the shell with your command, which has the effect of returning the command's result.

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.