shell脚本多次执行命令从输入文件读取值
问题描述:
我有一个输入文件input.txt,我想运行一个命令,它应该从input.txt中读取两个值。让我们假设源名称和目标名称应该从输入和相同的命令中读取,根据input.txt重复数千次。shell脚本多次执行命令从输入文件读取值
此外,每个命令的输出都存储在单独的日志中。这是可能的一个单一的输入文件,或者我们需要使用2个文件的源和目的地?请求您提供用于实现此目的的shell脚本,因为我在shell脚本中很差。我尝试了下面的不工作。
while read i j; do
command $i $j
done > output.txt
答
当然可以。假设这是input.txt
:
source1.txt dest1.txt
source2.txt dest2.txt
...
而要做到这一点:
command source1.txt dest1.txt
command source2.txt dest2.txt
...
这里有一个办法:
while read i o; do
command $i $o
done < input.txt
这假定命令command
已经构建读取从它的第一争论并写入第二个。如果command
改为打印到标准输出(即,到终端屏幕),则将command $i $o
替换为command $i > $o
。这也假定input.txt
中没有空格或有趣的字符。
如果您的input.txt
包含例如百万行或多个:
awk '{printf "command %s\n", $0}' input.txt | sh
或者,如果你必须使用command $i > $o
:
awk '{printf "command %s > %s\n", $1, $2}' input.txt | sh
这种方法从input.txt中,并打印command source1.txt dest1.txt
线的第一线,command source2.txt dest2.txt
第二,等...然后它“管”(|
)这些命令sh,执行它们。
对于错误command
处理,尝试:
while read i o; do
command $i $o || command2 $i $o >> command2.log
done < input.txt 2> error.log
或者:
done <input.txt> error.log 2>&1
(其中之一将更好地工作,这取决于是否command
和command2
打印他们的错误到标准输出(1)或者stderr(2)。)
答
假设你想在不同的文件不同的输出,然后在每个命令的每个命令日志文件和一个错误文件:
while read i o; do
command $i $o 2>"$i$o.err" >"$i$o.log"
done < input.txt
错误并登录同一个文件:stderr
被重定向到stdout
感谢2>&1
:
while read i o; do
command $i $o 2>&1 >"$i$o.log"
done < input.txt
您也可以在所有相同的文件output.log
:
echo "" > output.log
while read i o; do
command $i $o 2>&1 >> output.log
done < input.txt
谢谢韦伯,我试过它有效。但是我在某些命令中失败了,是否有任何方法可以检查结果,如果失败了,我们应该在其中轻微修改来运行命令。每条命令执行完日志详细信息后都会加载到日志文件中。像下面一样读到i o;做 命令$ I $Ø \t如果结果(好) \t下一个迭代 \t其他 \t命令2 $ I $Ø 做输出log.txt的 – Hemanth
加入请求的错误处理 – webb