Return Values
In BASH scripting, functions often need to communicate results back to the caller. While functions can use return to signal success or failure, BASH also supports returning arbitrary data via standard output. Understanding these mechanisms is critical for writing robust, reusable scripts.
Exit Codes as Return Values¶
BASH functions return exit codes by default, which are integers between 0 and 255. By convention:
- 0 indicates success
- Non-zero values indicate errors (e.g., 1 for general errors, 2 for syntax errors)
Use the return keyword to set the exit code:
Check the exit code using $?:
Example: File Existence Check¶
check_file() {
if [ -f "$1" ]; then
return 0
else
return 1
fi
}
check_file /path/to/file
echo "Exit code: $?"
Output Redirection for Data Return¶
For returning structured data (strings, numbers, or complex values), redirect standard output:
Capture the output using command substitution:
Example: Returning a Status Message¶
Combining Both Methods¶
Functions can use both exit codes and output redirection:
process_data() {
if [ -z "$1" ]; then
echo "Error: No input provided"
return 1
fi
echo "Processed: $1"
return 0
}
Best Practices and Considerations¶
- Use exit codes for status (success/failure) and output redirection for data.
- Avoid relying on exit codes for detailed error messages; use output redirection for clarity.
- For functions that need to return multiple values, use output redirection with arrays or JSON.
- Always validate inputs and handle edge cases to prevent unexpected behavior.
Key takeaways¶
- BASH functions return exit codes (0-255) by default, with
0indicating success. - Use
returnto set exit codes and$?to check them. - Redirect standard output (
echo) to return arbitrary data to the caller. - Combine exit codes and output redirection for robust error handling and data transfer.