如何在bash shell中重定向命令输出? [英] how to redirect command output in bash shell?
问题描述
我在编写一个小的bash命令时遇到了问题.基本上,我想回显wrapper命令并将真实命令的输出重定向到日志文件.
I'm having a problem writing a small bash command. Basically I want to echo the wrapper command and redirect the output of the real command to a log file.
.bashrc中的类似内容不起作用-输出仍进入控制台.
Something like this in my .bashrc doesn't work -- the output still gets to the console.
cmd="some_command >& output.log";
echo $cmd;
$cmd;
但是下面的工作-输出直接进入日志文件.
But the following works -- the output is directed into the log file.
cmd = "some_command";
echo $cmd" >& output.log";
$cmd >& output.log;
第一种方法有什么问题?如何解决?
What is wrong with the first method? How to fix it?
谢谢!
推荐答案
第一种方法有什么问题?
What is wrong with the first method?
在变量中包含重定向运算符时,shell不会将其视为特殊字符.而是将它们视为有关程序的参数.
When you include the redirection operators within a variable, the shell doesn't treat those as special. Instead those are considered as arguments to the program in question.
一种解决方案是利用eval
:
cmd="some command >& output.log";
eval $cmd;
顺便说一句,以下是错误的:
As an aside, the following is wrong:
cmd = "some command";
在变量分配中,=
周围不能有空格.
You cannot have spaces around =
in a variable assignment.
这篇关于如何在bash shell中重定向命令输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!