...
Unlike most other programming languages, bash functions and scripts can only return a single integer between 0 and 255. By convention a return value of 0 means success (true), and any other return value is an error code (false).
A function can return this value using the return keyword (e.g. return 0
). The return value is then stored in the special $? variable, which can be checked by the caller. Since this not very much information, function return values are not often used or checked. Instead, as we've seen, functions are often called for their standard output, which serves as a return value proxy.
...
Tip | ||
---|---|---|
| ||
We will do this in a new tmux or screen session, since accidentally calling exit at top-level (instead of in a sub-shell) will log you off the server! See this nice tmux cheat sheet: http://atkinsam.com/documents/tmux.pdf |
Code Block | ||
---|---|---|
| ||
# Invoke tmux from your login command line tmux new # Now you're in a tmux. Mine has a green bar at the bottom ( exit 0 ) echo $? ( exit 255 ) res=$? echo "exit code: $res" # exit tmux session exit # You're back at your login command line now |
More on capturing output
We've already seen some examples of capturing output from echo using backtick evaluation. Now let's read the contents of a file into a variable using parentheses evaluation.
...
Rather than checking an exit code, it is often more robust to sanity check the returned output; for example, checking to see if it is empty:. If you execute this in your tmux, be sure to enclose it all in parentheses or else your tmux will exit!
Code Block | ||
---|---|---|
| ||
dat=$( cat not_a_file ) if [[ "$dat" == "" ]]; then echo "ERROR: no data found" 1>&2; exit 255 else echo "Data is: '$dat'" fi # or using -z to test for an empty string if [[ -z "$dat" ]]; then echo "ERROR: no data found" 1>&2; exit 255; else echo "Data is '$dat'"; fi |
See https://www.gnu.org/software/bash/manual/html_node/Bash-Conditional-Expressions.html for conditional expressions, and https://www.gnu.org/software/bash/manual/html_node/Conditional-Constructs.html for conditional constructs such as if or case.
Setting environment variables for a script
...