在单个文件上运行多个Shell命令并将输出重定向到同一文件

问题描述 投票:1回答:1

这是一个相当笨拙的问题,因为我知道如何使它正常工作,但现在无法弄清楚语法。

我有一个shell脚本,它基本上检查文件大小并将其重定向到一个临时文件

#!/bin/bash
while true
do
    echo "Press CTRL+C to stop the script execution"

echo "*********************" >> /tmp/size.txt
echo "current date is" >> /tmp/size.txt
date >> /tmp/size.txt
echo "size of file r4" >> /tmp/size.txt
du -h /tmp/r4
echo "size of file h5" >> /tmp/size.txt
du -h /var/h5
echo "size of file h6" >> /tmp/size.txt
du -h /opt/h6
echo "size of file h8" >> /tmp/size.txt
du -h /data/h8
echo "*********************" >> /tmp/size.txt
end

上面的脚本运行完美,可以连续记录所有数据。但是,我需要编写重定向(/tmp/size.txt)太多次,以使脚本显得笨拙。我以前可以做到,但由于语法看起来不正确,因此不起作用。

我能在这里获得帮助吗,所以我不需要重复重定向,只需一行即可处理。

谢谢

bash shell sh stdout io-redirection
1个回答
1
投票

>> /tmp/size.txt移到done后,从内部删除:

while true
do
   echo "Press CTRL+C to stop the script execution"

   echo "*********************"
   echo "current date is"
   date >> /tmp/size.txt
   echo "size of file r4"
   du -h /tmp/r4
   echo "size of file h5"
   du -h /var/h5
   echo "size of file h6"
   du -h /opt/h6
   echo "size of file h8"
   du -h /data/h8
   echo "*********************"
done >> /tmp/size.txt
© www.soinside.com 2019 - 2024. All rights reserved.