Returning information from functions
You have learned to pass command-line parameters to functions. Similarly, the function can return integers as a return value. Normally, functions return either TRUE or FALSE. In certain cases, the function can return integer values, such as 5 or 10, as well.
The syntax is:
return N
When the function calls the command return, the function exits with the value specified by N
.
If the function does not call the command return, then the exit status returned is that of the last command executed in the function. If what we need is the status of the last command executed in the function, then we need not return any value from the function. This is illustrated in the following script function_14.sh
:
#!/bin/bash is_user_root() { [ $(id -u) -eq 0 ]; } is_user_root && echo "You are root user, you can go ahead."\ || echo "You need to be administrator to run this script"
Test the script as follows:
$ chmod +x function_14.sh $ ./function_14.sh
If you are a root...