Returning from a function
From Linux Shell Scripting Tutorial - A Beginner's handbook
- In mathematics a function ƒ takes an input, x, and returns an output ƒ(x).
- In computer a shell function name can take an input, $1 and return back the value (true or false) to the script.
- In other words, you can return from a function with an exit status.
Syntax
- The return command causes a function to exit with the return value specified by N and syntax is:
return N
- If N is not specified, the return status is that of the last command.
- The return command terminates the function.
- The return command is not necessary when the return value is that of the last command executed.
Example
Create a shell script called isroot.sh as follows:
#!/bin/bash # version 1.0 # Purpose: Determine if current user is root or not is_root_user(){ [ $(id -u) -eq 0 ] } # invoke the function # make decision using conditional logical operators is_root_user && echo "You can run this script." || echo "You need to run this script as a root user."
Save and close the file. Run it as follows:
chmod +x isroot.sh ./isroot.sh
Sample outputs:
You need to run this script as a root user.
Run it as the root user:
sudo ./isroot.sh
Sample outputs:
[sudo] password for vivek: You can run this script.
The following is an updated version of the same script. This version create the constants variables using the declare command called TRUE and FALSE.
#!/bin/bash # version 2.0 # define constants declare -r TRUE=0 declare -r FALSE=1 # Purpose: Determine if current user is root or not is_root_user(){ # root user has user id (UID) zero. [ $(id -u) -eq 0 ] && return $TRUE || return $FALSE } is_root_user && echo "You can run this script." || echo "You need to run this script as a root user."
Returning a string or word from a function
- You cannot return a word or anything else from a function.
- However, you can use echo or printf command to send back output easily to the script.
#!/bin/bash # Variables domain="CyberCiti.BIz" out="" ################################################################## # Purpose: Converts a string to lower case # Arguments: # $@ -> String to convert to lower case ################################################################## function to_lower() { local str="$@" local output output=$(tr '[A-Z]' '[a-z]'<<<"${str}") echo $output } # invoke the to_lower() to_lower "This Is a TEST" # invoke to_lower() and store its result to $out variable out=$(to_lower ${domain}) # Display back the result from $out echo "Domain name : $out"