Bash - Return value from subscript to parent script

Bash

Bash Problem Overview


I have two Bash scripts. The parent scripts calls the subscript to perform some actions and return a value. How can I return a value from the subscript to the parent script? Adding a return in the subscript and catching the value in the parent did not work.

Bash Solutions


Solution 1 - Bash

I am assuming these scripts are running in two different processes, i.e. you are not "sourcing" one of them.

It depends on what you want to return. If you wish only to return an exit code between 0 and 255 then:

# Child (for example: 'child_script')
exit 42

# Parent
child_script
retn_code=$?

If you wish to return a text string, then you will have to do that through stdout (or a file). There are several ways of capturing that, the simplest is:

# Child (for example: 'child_script')
echo "some text value"

# Parent
retn_value=$(child_script)

Solution 2 - Bash

Here is another way to return a text value from a child script using a temporary file. Create a tmp file in the parent_script and pass it to the child_script. I prefer this way over parsing output from the script

Parent

#!/bin/bash
# parent_script
text_from_child_script=`/bin/mktemp`
child_script -l $text_from_child_script
value_from_child=`cat $text_from_child_script`
echo "Child value returned \"$value_from_child\""
rm -f $text_from_child_script
exit 0

Child

#!/bin/bash
# child_script
# process -l parm for tmp file

while getopts "l:" OPT
do
    case $OPT in
      l) answer_file="${OPTARG}"
         ;;
    esac
done

read -p "What is your name? " name

echo $name > $answer_file

exit 0
      

Solution 3 - Bash

return a value from the subscript and check the variable $? which contain the return value

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1049697View Question on Stackoverflow
Solution 1 - BashcdarkeView Answer on Stackoverflow
Solution 2 - BashGoinOffView Answer on Stackoverflow
Solution 3 - BashNagasakiView Answer on Stackoverflow