我想在函数中打印 echo 并返回值。它不起作用:
function fun1() {
echo "Start function"
return "2"
}
echo $(( $(fun1) + 3 ))
Run Code Online (Sandbox Code Playgroud)
我只能打印回声:
function fun1() {
echo "Start function"
}
fun1
Run Code Online (Sandbox Code Playgroud)
或者我只能返回值:
function fun1() {
echo "2" # returning value by echo
}
echo $(( $(fun1) + 3 ))
Run Code Online (Sandbox Code Playgroud)
但我不能两者兼得。
好吧,根据您的意愿,有几种解决方案:
将消息打印到stderr您希望接收的值stdout。
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 ))
Run Code Online (Sandbox Code Playgroud)将消息正常打印到stdout并使用实际返回值$?。
请注意,返回值将始终是来自0- 255(感谢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 ))
Run Code Online (Sandbox Code Playgroud)只需使用全局变量。
# 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 ))
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
14131 次 |
| 最近记录: |