62

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.

1

3 Answers 3

88

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)
4
  • 6
    Does the echo method return everything echo'd by the child script or just the last line?
    – Akhil F
    Commented May 21, 2015 at 23:43
  • 3
    @AakilFernandes: in this case, echo writes the line given to it: "some text value" in the example. However, the parent is capturing all the standard output from the child, whether it came from an echo or not. That could be multiple lines separated by newlines $'\n'
    – cdarke
    Commented May 22, 2015 at 7:48
  • 2
    @cdarke What if i just want the last line to be captured by the parent? Commented Jan 24, 2022 at 21:43
  • 1
    @SaltukKezer you can use tail -1 to get the last line
    – user3091996
    Commented Feb 22, 2022 at 16:49
5

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
-3

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

3
  • 5
    "Return" is ambiguous here, as the return statement can only be used to return from a function, not a script. To be precise, you need to use the exit statement to return from the script.
    – chepner
    Commented May 2, 2013 at 13:25
  • 2
    @chepner: actually return can also be used from a "sourced" file ( . or source command), but is that then a script?
    – cdarke
    Commented May 2, 2013 at 13:52
  • Ah, tricky. I guess the right answer then is "use return or exit as appropriate".
    – chepner
    Commented May 2, 2013 at 14:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.