return value from shell script function

How to Return Value in Shell Script Function

Sometimes you may need to return a value from a called function in shell script. Unfortunately, there is no direct way to do this as available in other programming languages. However, there are three workarounds to return value in shell script. In this article, we will look at how to return value from a function in shell script.


How to Return Value in Shell Script Function

Here are the different ways to return value in shell script function.


1. Using Echo

You can echo string at the end of your Shell script function. In fact you can echo strings throughout your function if you want. Here is an example test.sh shell script file.

#!/bin/sh 

# Define your function here 
test () {    echo "Hello World" } 

#Invoke function
test

You can call it from terminal. When you run this script, it will call test function, which echoes “Hello World” text.

$ ./test.sh
Hello World


2. Return Exit Status

You may also return an exist status at the end of your shell script function as shown below. However, exit status can only be a number between 0 and 255.

#!/bin/sh 

# Define your function here 
test () {    return 49 } 

#Invoke function
test
echo $?

In this case, the exit status returned by your shell function is stored in $? which can be dislayed using echo. When you run this shell script, it will return 49 which is stored in $?. So you will get the output as 49. By the way, $? always stores the exit status of the most recently run command in Linux.

$ ./test.sh
49


3. Using Shared Variable

In this case, you can use a shared variable that you set within your shell script function and then use it afterwards. Here is an example. Here we define a variable test_var outside the shell function, then set its value within the function, and use it afterwards.

#!/bin/sh 

test_var=0
# Define your function here 
test () {    test_var = 39 } 

#Invoke function
test
if [ $test_var == 0 ]
then
    echo "variable not set"
else
    echo "variable is set"
fi

When you run the shell script function, it will set the value of test_var, which is used to echo the appropriate message.

$ ./test.sh
variable is set

In this article, we have seen three workarounds to return a value from function called in shell script.

Also read:

How to Run Python Script in Django Shell
How to Disable Foreign Key Constraint in MySQL
How to Loop Through List in Django Template
How to Convert PDF to Image/JPG in Linux
How to Fix NGINX Upstream Timed Out Error

Leave a Reply

Your email address will not be published. Required fields are marked *