Let's imagine I have a bash script, where I call this:
bash -c "some_command" do something with code of some_command here
Is it possible to obtain the code of some_command
? I'm not executing some_command
directly in the shell running the script because I don't want to alter it's environment.
Use signals to exit process from subshell This is the mechanism that allows you to exit a command line process by pressing ctrl-c. When you press ctrl-c in your terminal, an interrupt signal (SIGINT) is sent to the current process.
To check the exit code we can simply print the $? special variable in bash. This variable will print the exit code of the last run command.
Launch a terminal, and run any command. Check the value of the shell variable “$?” for the exit code. $ echo $? As the “date” command ran successfully, the exit code is 0.
Use return . The return bash builtin will exit the sourced script without stopping the calling (parent/sourcing) script. Causes a function to stop executing and return the value specified by n to its caller.
$?
will contain the return code of some_command
just as usual.
Of course it might also contain a code from bash, in case something went wrong before your command could even be executed (wrong filename, whatnot).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With