Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a string be returned from a Bash function without using echo or global variables?

I'm returning to a lot of Bash scripting at my work, and I'm rusty.

Is there a way to return a local value string from a function without making it global or using echo? I want the function to be able to interact with the user via screen, but also pass a return value to a variable without something like export return_value="return string". The printf command seems to respond exactly like echo.

For example:

function myfunc() {
    [somecommand] "This appears only on the screen"
    echo "Return string"
}

# return_value=$(myfunc)
This appears only on the screen

# echo $return_value
Return string
like image 931
RightmireM Avatar asked Jan 23 '13 15:01

RightmireM


People also ask

Can a bash function 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.

How do I return a value from a function in bash?

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 $? .

Can a bash script return a value?

Bash Function ReturnBash functions differ from most programming languages when it comes to returning a value from a function. By default, bash returns the exit status of the last executed command in the function's body.

Do bash functions have access to global variables?

By default, every variable in bash is global to every function, script and even the outside shell if you are declaring your variables inside a script.


1 Answers

No. Bash doesn't return anything other than a numeric exit status from a function. Your choices are:

  1. Set a non-local variable inside the function.
  2. Use echo, printf, or similar to provide output. That output can then be assigned outside the function using command substitution.
like image 106
Todd A. Jacobs Avatar answered Sep 30 '22 03:09

Todd A. Jacobs