The shell is designed to be a command interpreter. Shell scrips language, if we can call it so, Initially was used to automate simple administrative tasks and flows.

Shell scripting was not designed to give all structural languages facilities, as Python or Perl, for instance. Nevertheless shell scripting, was and it is intensive used by most of unix and DBA’s administrators, scripts reaching several hundred lines of code, in many cases spread over several functions and files.

Among others, one of big shell scripting limitation is the return values from functions.

With no return keyword, the function returned value is the last executed return code of the last command executed in the function. This situation cannot be accepted for a production script, as this is totally arbitrary as returned value.

#!/bin/bash
function my_function() {
    mkdir /cannot/create/this/directory
}

# Execute the my_function
my_function
ret=$?
echo "The returned value: $ret"

Output (The returned value is the error code value of the failing mkdir command):

mkdir: cannot create directory ‘/cannot/create/this/directory’: No such file or directory
The returned value: 1

Otherwise the return value it the numerical value of the return keyword, if it is used. This situation is better than the previous one, but pretty limitative to only numerical values (in fact this is the most used use-case for shell function returns) :

#!/bin/bash
function my_function() {
    return 99
}

# Execute the my_function
my_function
ret=$?
echo "The returned value: $ret"

Output:

The returned value: 99

If there is a need to return one or more arbitrary values, like strings or paths, other method should be used:

#!/bin/bash
function my_function() {
    local _ret_val1=$1
    local _ret_val2=$2
    
    # ... your code here
    first_value_to_return="Hello world"
    second_value_to_return="/path/to/nowhere"

    # return values
    eval $_ret_val1="'$first_value_to_return'"
    eval $_ret_val2="'$second_value_to_return'"

    return 0
}

# Execute the my_function with parameter1 and parameter2
my_function parameter1 parameter2

function_return_code=$?

echo "First value is: $parameter1"
echo "Second value is: $parameter2"
echo "Function return code is: $function_return_code"

Output:

First value is: Hello world
Second value is: /path/to/nowhere
Function return code is: 0

The advantage of this method is that the numerical returned code can be still be used, by using the return keyword.

Conclusion

Despite limitation shell scripting is one of the most used “languages” for system admins, DBA’s. Even if there are big limitation, work arounds, like the one presented, exist for any situation.


Share on