执行命令列表并将输出存储到列表

时间:2017-04-25 09:40:18

标签: bash parallel-processing pipe output

我收到命令流作为输入:

command1
command2
command3

由此,我想创建一个包含以下内容的文件output.txt

command1 output1
command2 output2
command3 output3

output_icommand_i的输出(每个命令返回一个整数)。我可以依次使用parallelpaste来做到这一点,但我想知道是否有办法在单个bash调用中获取output.txt

EDIT 使用parallel,我就是这样做的:

cat commands.txt | parallel -k > outputs_only.txt
paste commands.txt outputs_only.txt > outputs.txt

1 个答案:

答案 0 :(得分:2)

只是bash中的循环,包含命令的文件的输入重定向

#!/bin/bash

while read -r line; do 
    echo "$line" "$(eval "$line")"
done < commands.txt > output.txt

单行

while read -r line; do echo "$line" "$(eval "$line")"; done < commands.txt > output.txt

如果您想要从stdin而不是从文件中读取,只需管道流到循环,

< command-producing-stream > | while read -r line; do echo "$line" "$(eval "$line")"; done > output.txt