[SOLVED] 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


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.

Answered By – Todd A. Jacobs

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *