Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? Thanks!

like image 931
Bramat Avatar asked Nov 08 '17 10:11

Bramat


People also ask

Can bash scripts return values?

Return Values Unlike functions in “real” programming languages, Bash functions don't allow you to return a value when called. 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.

Can a script return a value?

A return is a value that a function returns to the calling script or function when it completes its task. A return value can be any one of the four variable types: handle, integer, object, or string.

Can a bash script return a string?

Bash function can return a string value by using a global variable. In the following example, a global variable, 'retval' is used. A string value is assigned and printed in this global variable before and after calling the function. The value of the global variable will be changed after calling the function.


2 Answers

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 )
like image 167
choroba Avatar answered Sep 19 '22 00:09

choroba


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.

like image 45
Tom Fenech Avatar answered Sep 22 '22 00:09

Tom Fenech