【问题标题】:Run multiple shell commands on a single file and redirect the output to the same file在单个文件上运行多个 shell 命令并将输出重定向到同一个文件
【发布时间】:2020-02-26 20:04:39
【问题描述】:

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

我有一个 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】:

    done 之后移动>> /tmp/size.txt 并将其从内部移除:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多