Can a string be returned from a Bash function without using echoes or globals?
I go back to a lot of Bash scripting in 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 through the screen, but also pass the return value to a variable without something like export return_value="return string"
. The printf command seems to respond in exactly the same way as 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
+3
RightmireM
source
to share
2 answers
Not. Bash returns nothing but the numeric exit status of the function. Your choice:
- Set a non-local variable inside the function.
- Use
echo
,printf
or similar for output. This output can then be assigned outside of the function using command substitution.
+6
Todd A. Jacobs
source
to share
To make it only appear on screen, you can redirect the echo to stderr:
echo "This is only displayed on screen"> & 2
Obviously stderr shouldn't be redirected.
+2
German garcia
source
to share