通过一个shell脚本打开/closures将数据附加到文件

我需要调整我的shell脚本并多次写入$log 。 重复打开和closures文件将导致运行时间的增加。

我怎样才能把一切写到文件中,包括我的脚本中定义的所有echo语句?

 #!/bin/sh log="loadlog.log" for i in {1..10} do n=$((100*$i)) echo "## Users=$i requests=$n ##" >> $log ab -n $n -c $i http://mainserver.com/index.html >> $log ssh root@mainserver cat /proc/loadavg >> $log echo "======" >> $log done 

我不确定,但是我想你只想打开日志文件来写一次,是吗?

如果是这样,你需要使用一个子shell,输出到STDOUT,然后在外面把它发送到日志文件。

 #! /bin/bash log="loadlog.log" ( for i in {1..10}; do n=$((100*$i)) echo "## Users=$i requests=$n ##" ab -n $n -c $i http://mainserver.com/index.html ssh root@mainserver cat /proc/loadavg echo "======" done ) >> $log 

另外,我build议你用你的代码风格来做一些事情,这是不可读的。 而且,您需要使用#!/bin/bash因为您在循环中使用了bash特定的构造。

在redirect中使用exec命令将redirect应用于整个脚本。 所以,你可以redirect所有的stdout追加到日志文件:

 #!/bin/sh log="loadlog.log" exec 1>>$log for i in {1..10} do n=$((100*$i)) echo "## Users=$i requests=$n ##" ab -n $n -c $i http://mainserver.com/index.html ssh root@mainserver cat /proc/loadavg echo "======" done 

如果你还想把东西发给用户,你可以先制作一个stdout的副本:

 #!/bin/sh log="loadlog.log" exec 3>&1 # file descriptor 3 is now stdout exec 1>>$log for i in {1..10} do # ... echo "======" # this line will be appended to the log file echo "completed loop $i" >&3 # this line will be displayed to user done exec 1>&3 # fd 1 restored to stdout exec 3>&- # fd 3 is closed echo "stdout now restored"