I want print echo in function and return value. It's not working:
function fun1() { echo "Start function" return "2"
}
echo $(( $(fun1) + 3 ))I can only print echo:
function fun1() { echo "Start function"
}
fun1Or I can only return value:
function fun1() { echo "2" # returning value by echo
}
echo $(( $(fun1) + 3 ))But I can't do both.
13 Answers
Well, depending on what you wish, there are several solutions:
Print the message to
stderrand the value you wish to take instdout.function fun1() { # Print the message to stderr. echo "Start function" >&2 # Print the "return value" to stdout. echo "2" } # fun1 will print the message to stderr but $(fun1) will evaluate to 2. echo $(( $(fun1) + 3 ))Print the message normally to
stdoutand use the actual return value with$?.
Note that the return value will always be a value from0-255(Thanks Gordon Davisson).function fun1() { # Print the message to stdout. echo "Start function" # Return the value normally. return "2" } # fun1 will print the message and set the variable ? to 2. fun1 # Use the return value of the last executed command/function with "$?" echo $(( $? + 3 ))Simply use the global variable.
# Global return value for function fun1. FUN1_RETURN_VALUE=0 function fun1() { # Print the message to stdout. echo "Start function" # Return the value normally. FUN1_RETURN_VALUE=2 } # fun1 will print the message to stdout and set the value of FUN1RETURN_VALUE to 2. fun1 # ${FUN1_RETURN_VALUE} will be replaced by 2. echo $(( ${FUN1_RETURN_VALUE} + 3 ))
With additional variable (by "reference"):
function fun1() { echo "Start function" local return=$1 eval $return="2"
}
fun1 result
echo $(( result + 3 )) A funny resolution could be tailing the last line of fun1() as a returned value:
function fun1() { echo "Start function" echo "return:" echo "2"
}
# Create a temporary file
output=$(mktemp)
# Run and redirect the output to console and to file simultaneously
fun1 |& tee $output
# Get the last line of the file into returnValue
returnValue=$(tail -1 $output)
echo $(( $returnValue + 3 ))