Bash 脚本 - shell 命令输出重定向

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/519395/
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-09 17:55:33  来源:igfitidea点击:

Bash Scripting - shell command output redirection

bashshellscripting

提问by RomanM

Can someone help explain the following:

有人可以帮助解释以下内容:

If I type:

如果我输入:

a=`ls -l`

Then the output of the ls command is saved in the variable a

然后ls命令的输出保存在变量中 a

but if I try:

但如果我尝试:

a=`sh ./somefile`

The result is outputed to the shell (stdout) rather than the variable a

结果输出到 shell ( stdout) 而不是变量a

What I expected was the result operation of the shell trying to execute a scrip 'somefile' to be stored in the variable.

我期望的是 shell 尝试执行somefile要存储在变量中的脚本 ' '的结果操作。

Please point out what is wrong with my understanding and a possible way to do this.

请指出我的理解有什么问题以及可能的方法。

Thanks.

谢谢。

EDIT:

编辑:

Just to clarify, the script 'somefile' may or may not exist. If it exsists then I want the output of the script to be stored in 'a'. If not, I want the error message "no such file or dir" stored in 'a'

只是为了澄清,脚本“ somefile”可能存在也可能不存在。如果它存在,那么我希望脚本的输出存储在“ a”中。如果没有,我希望错误消息“没有这样的文件或目录”存储在 ' a'

回答by paxdiablo

I think because the shell probably attaches itself to /dev/tty but I may be wrong. Why wouldn't you just set execute permissions on the script and use:

我认为是因为 shell 可能将自身附加到 /dev/tty 但我可能是错的。为什么不直接在脚本上设置执行权限并使用:

a=`./somefile`

If you want to capture stderr andstdout to a, just use:

如果要将 stderrstdout捕获到 a,只需使用:

a=`./somefile 2>&1`

To check file is executable first:

首先检查文件是否可执行:

if [[ -x ./somefile ]] ; then
    a=$(./somefile 2>&1)
else
    a="Couldn't find the darned thing."
fi

and you'll notice I'm switching to the $() method instead of backticks. I prefer $() since you can nest them (e.g., "a=$(expr 1 + $(expr 2 + 3))").

你会注意到我正在切换到 $() 方法而不是反引号。我更喜欢 $() 因为你可以嵌套它们(例如,“ a=$(expr 1 + $(expr 2 + 3))”)。

回答by Bogdan

You can try the new and improved way of doing command substitution, use $() instead of backticks.

您可以尝试新的和改进的命令替换方式,使用 $() 代替反引号。

a=$(sh ./somefile)

If it still doesn't work, check if somefileis not actually stderr'ing.

如果它仍然不起作用,请检查somefile是否实际上不是stderr

回答by phihag

You are correct, the stdout of ./somefileis stored in the variable a. However, I assume somefile outputs to stderr. You can redirect that with 2>&1directly after ./somefile.

你是对的,标准输出./somefile存储在变量中a。但是,我假设 somefile 输出到 stderr。您可以2>&1直接在./somefile.