Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - Return value from subscript to parent script

Tags:

bash

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.

like image 329
user1049697 Avatar asked May 02 '13 12:05

user1049697


People also ask

How do I return a value from a bash script?

Return Values When a bash function completes, its return value is the status of the last statement executed in the function, 0 for success and non-zero decimal number in the 1 - 255 range for failure. The return status can be specified by using the return keyword, and it is assigned to the variable $? .

How do I return a value from one shell script to another?

The construct var=$(myfunction) captures the standard out from myfunction and saves it in var . Thus, when you want to return something from myfunction , just send it to standard, like we did with echo in the example above.

Can a shell script return a value?

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.


2 Answers

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) 
like image 160
cdarke Avatar answered Sep 28 '22 02:09

cdarke


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 
like image 43
GoinOff Avatar answered Sep 28 '22 02:09

GoinOff