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
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.
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 $? .
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.
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.
No. Bash doesn't return anything other than a numeric exit status from a function. Your choices are:
echo
, printf
, or similar to provide output. That output can then be assigned outside the function using command substitution.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With