使用bash -c与循环和标准输出重定向 [英] Using bash -c with loops and standard output redirection
问题描述
为什么从以下命令输出的标准有何不同?
命令1:
为((i = 0;我小于10,I = I + 1));做回声$ I; DONE
命令2:
的bash -c为((i = 0;我小于10,I = I + 1));做回声$ I;完成
命令1打印整数1至10在单独一行,符合市场预期。命令2 10打印在每行
什么我需要做的就是命令2打印同样的事情命令1?
长的故事:
我经常需要运行大量文件的可执行和捕捉的全过程的输出。我使用了一个类似的循环称为my_script.sh一个单独的文件为Command。
我然后可以使用得到的输出:
庆典my_script.sh> RESULTS.TXT
由于这是一个痛苦位创造平凡的循环单独my_script.sh的文件,我希望用的bash -c来达到同样的事情,但遇到了这个问题。
感谢您的任何建议。期待回复。结果
米莎
什么我需要做的就是命令2打印同样的事情命令1?
块引用>您需要修改该行:
的bash -c为((i = 0;我小于10,I = I + 1));做回声$ I;完成
要,而不是这样说:
的bash -c为((i = 0;我小于10,I = I + 1));做回声\\ $ I;完成
这是怎么回事的是,
$ I
顺序由您从运行bash外壳PTED是间$ P $,它取代的自己的的I
变量到串其传递到新的bash实例之前执行。因此由时间的新的bash看到串,它是:为((i = 0;我小于10,I = I + 1));做呼应10; DONE
假设
I
包含的值10。(当我第一次跑第二个脚本,我做到了运行第一之前,写了10空行,因为我没有
I
变量定义的,因此它被代入空字符串)。Why does the standard output from the following commands differ?
command1:
for ((i=0; i<10; i=i+1)); do echo $i; done
command2:
bash -c "for ((i=0; i<10; i=i+1)); do echo $i; done"
command1 prints the integers 1 to 10 on a separate line, as expected. command2 prints 10 on each line.
What do I need to do to get command2 to print the same thing as command1?
The long story:
I often need to run an executable on a large number of files and capture the output of the entire process. I use a for loop similar to command1 in a separate file called my_script.sh.
I can then get the output using:
bash my_script.sh > results.txt
Since it's a bit of a pain to create a separate my_script.sh file for trivial for loops, I was hoping to achieve the same thing by using "bash -c", but ran into this problem.
Thanks for any suggestions. Looking forward to replies.
Misha解决方案What do I need to do to get command2 to print the same thing as command1?
You need to fix this line:
bash -c "for ((i=0; i<10; i=i+1)); do echo $i; done"
To say this instead:
bash -c "for ((i=0; i<10; i=i+1)); do echo \$i; done"
What's happening is that the
$i
sequence is being interpreted by the shell you are running bash from, and it is substituting its owni
variable into the string before passing it off to the new bash instance to be executed. So by the time the new bash sees the string, it is:for ((i=0; i<10; i=i+1)); do echo 10; done
Assuming that
i
contained the value "10".(When I first ran the second script, which I did before running the first, it wrote out 10 blank lines, because I had no
i
variable defined, and so it was substituting in the empty string.)这篇关于使用bash -c与循环和标准输出重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!