KandZ – Tuts

We like to help…!

Linux CLI 58 🐧 shell functions part 2

a - shell functions return codes
function return codes are used to indicate the success or failure of a function's execution.
also known as exit statuses
a return code of 0 indicates successful execution
while any other value indicates an error or failure.
return 0 → returns 0 for successful execution
return 1 → return 1 for non succesful execution
check_success $? → $? captures the return code

b - shell function exit command and local variables
exit command terminates a script execution based on some condition
You can also return code using exit commad
exit 0 → terminates execution with return code 0
exit 1 → terminates execution with return code 1
local variables are used to define variables within a specific scope or context inside a function.
These variables are not accessible outside the function
They do not affect or interfere with global variables of the same name.
local result=$1 → declares a local variable with the name result

c - shell functions error handling
Error handling is an essential aspect of writing robust shell scripts
strategies for implementing effective error handling in functions within your shell scripts:
using return codes
using set -e → automatically fails on error
using trap → Trap errors and handle them manually
Using set -u → automatically fails on undefined variables
set -e → exits immediately if a command exits with a non-zero status.
set -u → fails on an undefined variable.
trap 'echo "An error... → traps errors and handle them manually.

Leave a Reply