问题
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
回答1:
No. Bash doesn't return anything other than a numeric exit status from a function. Your choices are:
- Set a non-local variable inside the function.
- Use
echo
,printf
, or similar to provide output. That output can then be assigned outside the function using command substitution.
回答2:
To make it appear only in screen you can redirect echo to stderr:
echo "This appears only on the screen" >&2
Obviously, stderr should not be redirected.
回答3:
A creative use of the eval
function, you can also assign values to a parameters location, and effectively to your argument, within the body of a function. This is sometimes termed a "call-by-output" parameter.
foo() {
local input="$1";
# local output=$2; # need to use $2 in scope...
eval "${2}=\"Hello, ${input} World!\""
}
foo "Call by Output" output;
echo $output;
来源:https://stackoverflow.com/questions/14482943/can-a-string-be-returned-from-a-bash-function-without-using-echo-or-global-varia