0

I am trying to access a string returned by a shell script which was called from a parent shell script. Something like this:

ex.sh:

echo "Hemanth"

ex2.sh:

sh ex.sh

if [ $? == "Hemanth" ]; then
  echo "Hurray!!"
else
  echo "Sorry Bro!"
fi

Is there a way to do this? Any help would be appreciated.

Thank you.

2 Answers 2

3

Use a command substitution syntax on ex2.sh

valueFromOtherScript="$(sh ex.sh)"
printf "%s\n" "$valueFromOtherScript"

echo by default outputs a new-line character after the string passed, if you don't need it in the above variable use printf as

printf "Hemanth"

on first script. Also worth adding $? will return only the exit code of the last executed command. Its values are interpreted as 0 being a successful run and a non-zero on failure. It will NEVER have a string value as you tried to use.

0

A Bash script does not really "return" a string. What you want to do is capture the output of a script (or external program, or function, they all act the same in this respect).

Command substitution is a common way to capture output.

captured_output="$(sh ex.sh)"

This initializes variable captured_output with the string containing all that is output by ex.sh. Well, not exactly all. Any script (or command, or function) actually has two output channels, usually called "standard out" (file descriptor number 1) and "standard error" (file descriptor number 2). When executing from a terminal, both typically end up on the screen. But they can be handled separately if needed.

For instance, if you want to capture really all output (including error messages), you would add a "redirection" after your command that tells the shell you want standard error to go to the same place as standard out.

captured_output="$(sh ex.sh 2>&1)"

If you omit that redirection, and the script outputs something on standard error, then this will still show on screen, and will not be captured.

Another way to capture output is sending it to a file, and then read back that file to a variable, like this :

sh ex.sh > output_file.log
captured_output="$(<output_file.log)"

A script (or external program, or function) does have something called a return code, which is an integer. By convention, a value of 0 means "success", and any other value indicates abnormal execution (but not necessarily failure) : the meaning of that return code is not standardized, it is ultimately specific to each script, program or function.

This return code is available in the $? special shell variable immediately after the execution terminates.

sh ex.sh
return_code=$?
echo "Return code is $return_code"

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