9

I want to create a Bash file that returns a value. Meaning, in script script_a.bash I have a certain calculation, and script script_b.bash will call it.

script_a.bash:

return $1*5

script_b.bash:

a_value=./script_a.bash 3

when a_value will be 15.

I read a little bit about that, and saw that there's no "return" in bash, but something like this can be done in functions using "echo". I don't want to use functions, I need a generic script to use in multiple places.

Is it possible to return a value from a different script?

2
  • 1
    Use exit rc instead of return rc.
    – Chen A.
    Nov 8, 2017 at 10:15
  • It's not possible to return a value from a bash script. If you echo the result, the calling process can grab it. A numeric can be returned with exit but that's not recommended as this is represents a status code (and also some codes are reserved - so 'should' not be used). Nov 8, 2017 at 10:17

3 Answers 3

9

Use command substitution to capture the output of echo, and use arithmetic expression to count the result:

script_a.bash:

echo $(( $1 * 5 ))

script_b.bash

a_value=$( script_a.bash 3 )
7

Don't use return or exit, as they're for indicating the success/failure of a script, not the output.

Write your script like this:

#!/bin/bash

echo $(( $1 * 5 ))

Access the value:

a_value=$(./script_a.bash 3)

That is, use a $(command substitution) in the consuming code to capture the output of the script.

2
  • What if the script prints multiple output (e.g. some info via printf) and we only want the last output? e.g. inside a POSIX script if bash is found run bash -c with subscript, and this subscript has if statement that would alter the behaviour of the POSIX script? Jul 1, 2023 at 14:40
  • 1
    Command substitution will capture standard output, so the script can either make use of standard error (e.g. output status messages to >&2), or you can get the last line of the output using e.g. last_line=$(tail -n1 <<<"$a_value"). There are several answers on here explaining other methods.
    – Tom Fenech
    Jul 3, 2023 at 10:53
1

You can use exit rc;, but keep in mind that conventionally in *nix 0 is a successful result, any positive value is an error code. Is it an option to call

echo <your_value>;

and redirect output to the next binary called in the chain?

1
  • Also note exit status is limited to 0-255 - so OP's $1 could only be max of 85 :-) Nov 8, 2017 at 10:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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