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

旧街凉风 提交于 2019-12-23 10:16:49

问题


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:

  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.



回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!