Magazine

Returning Information from Functions in Linux Bash Script

Posted on the 27 April 2021 by Satish Kumar @satish_kumar86

You have learned topasscommand-line parameters to functions. Similarly, the function can return integers as a return value. Normally, functions return eitherTRUEorFALSE. In certain cases, the function can return integer values, such as5or10,as well.

The syntax is:

return N

When the function calls the command return, the function exits with the value specified byN.

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:

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 user, then the output will be as follows:

Output:

You are root user, you can go ahead.

If you are a normal user, then the output will be as follows:

Output:

You need to be administrator to run this script

A modified version of the previous script is function_15.sh:

function_15.sh

#!/bin/bash 
declare -r TRUE=0 
declare -r FALSE=1 
 
is_user_root() 
{ 
[ $(id -u) -eq 0 ] & return $TRUE || return $FALSE 
} 
is_user_root & echo "You can continue" || echo "You need to be root to run this script."

Test the script as follows:

$ chmod +x function_15.sh
$ ./function_15.sh

This should produce the following output:

Output:

You need to be root to run this script.

Let’s see the script in which the function returns a value:

#!/bin/bash 
yes_or_no() 
{ 
echo "Is your name $*?" 
while true 
do 
echo -n "Please reply yes or no :" 
read reply 
case $reply in 
Y | y | yes ) return 0;; 
N | n | no ) return 1;; 
*) echo "Invalid answer" 
esac 
done 
} 
 
if yes_or_no $1 
then 
echo"Hello $1 " 
else 
echo"name not provided" 
fi 

Test the script as follows:

$ chmod +x function_16.sh
$ ./function_16.sh Ganesh

This should produce the following output:

Output:

Is your name Ganesh?
Please reply yes or no : yes
Hello Ganesh

Returning a word or string from a function

In shell scripts, functions cannot return a word or string from a function. If we need to pass data to a script then we will have to store it in a global variable. We can even use echo or print to send data to a pipe or redirect it to the log file.


Back to Featured Articles on Logo Paperblog