I have a command that returns a number from 0 to n, and would like to catch that number and use as the exit code of the command itself. I was able to achieve it by doing this:
sh -c $'exit $(command)'
But it looks a little bit cumbersome for something so simple as using the stdout of a command and set it as the exit code. Do you know if there's a simpler way to do this?
If you want to capture output of a command then you need a command substitution, i.e. your $(command)
. If you want to deliver a specific exit status then that's either exit
or, in a function, return
.
If you want to do that output-to-exit-status conversion without terminating the shell, then using ()
to run it in a subshell is a better option than running it via sh -c
. Examples:
(exit "$(command)")
or
wrapper() {
return "$(command)"
}