回显输出到 BASH 函数内的终端

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27776665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:48:53  来源:igfitidea点击:

Echo output to terminal within function in BASH

bash

提问by McShaman

I am writing a script in BASH. I have a function within the script that I want to provide progress feedback to the user. Only problem is that the echo command does not print to the terminal. Instead all echos are concatenated together and returned at the end.

我正在用 BASH 编写脚本。我在脚本中有一个函数,我想向用户提供进度反馈。唯一的问题是 echo 命令不会打印到终端。相反,所有回声都连接在一起并在最后返回。

Considering the following simplified code how do I get the first echo to print in the users terminal and have the second echo as the return value?

考虑以下简化代码,如何在用户终端中打印第一个回显并将第二个回显作为返回值?

function test_function {
    echo "Echo value to terminal"
    echo "return value"
}

return_val=$(test_function)

回答by Robin Hsu

Yet a solution other than sending to STDERR (it may be preferred if your STDERR has other uses, or possibly be redirected by the caller)

然而,除了发送到 STDERR 之外的解决方案(如果您的 STDERR 有其他用途,或者可能被调用者重定向,则可能是首选)

This solution direct prints to the terminal tty:

此解决方案直接打印到终端 tty:

function test_function {
    echo "Echo value to terminal" > /dev/tty
    echo "return value"
}

回答by Jasen

send terminal output to stderr:

将终端输出发送到 stderr:

function test_function {
    echo "Echo value to terminal" >&2
    echo "return value"
}

回答by nu11p01n73R

Dont use command substitution to obtain the return value from the function

不要使用命令替换来获取函数的返回值

The return value is always available at the $?variable. You can use the variable rather than using command substitution

返回值始终在$?变量中可用。您可以使用变量而不是使用命令替换

Test

测试

$ function test_function {
> return_val=10; 
> echo "Echo value  to terminal $return_val";
> return $return_val; 
> }

$ test_function
Echo value  to terminal 10

$ return_value=$?

$ echo $return_value
10