Bramat
Bramat

Reputation: 997

return values from bash script

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?

Upvotes: 11

Views: 25035

Answers (3)

dimirsen Z
dimirsen Z

Reputation: 891

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?

Upvotes: 2

Tom Fenech
Tom Fenech

Reputation: 74595

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.

Upvotes: 9

choroba
choroba

Reputation: 241808

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 )

Upvotes: 11

Related Questions