庆典的重定向输出回路 [英] Redirecting output of bash for loop
问题描述
我有一个简单的bash命令看起来像
I have a simple BASH command that looks like
for i in `seq 2`; do echo $i; done; > out.dat
在此运行的输出以次2
是输出到终端,没有什么是输出到数据文件(out.dat)
When this runs the output of seq 2
is output to the terminal and nothing is output to the data file (out.dat)
我期待标准输出重定向到out.dat像它只需运行命令以次2 - ; out.dat
I am expecting standard out to be redirected to out.dat like it does simply running the command seq 2 > out.dat
推荐答案
删除您的分号。
for i in `seq 2`; do echo "$i"; done > out.dat
建议
也由Fredrik作为皮赫尔建议,尽量不要使用外部二进制文件不需要时,或至少在几乎没有:
Also as suggested by Fredrik Pihl, try not to use external binaries when they are not needed, or at least when practically not:
for i in {1..2}; do echo "$i"; done > out.dat
for ((i = 1; i <= 2; ++i )); do echo "$i"; done > out.dat
for i in 1 2; do echo "$i"; done > out.dat
此外,,可能会导致路径扩展词
小心的输出。
for A in $(echo '*'); do echo "$A"; done
将显示您的文件,而不仅仅是文字 *
。
$()
也被推荐为Bash和POSIX壳命令替换比反引号(更清晰的语法`
),并支持嵌套。
$()
is also recommended as a clearer syntax for command substitution in Bash and POSIX shells than backticks (`
), and it supports nesting.
该清洁解决方案,以及用于读取输出变量
The cleaner solutions as well for reading output to variables are
while read VAR; do
...
done < <(do something)
和
read ... < <(do something) ## Could be done on a loop or with readarray.
for A in "${ARRAY[@]}"; do
:
done
使用的printf也可以是相对于所述预定的功能更简单的替代方法:
Using printf can also be an easier alternative with respect to the intended function:
printf '%s\n' {1..2} > out.dat
这篇关于庆典的重定向输出回路的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!