anish anil
anish anil

Reputation: 2641

Run multiple shell commands on a single file and redirect the output to the same file

This is a rather clumsy question as i knew how to get this working but unable to figure out the syntax now.

I have a shell script which basically checks for the file size and redirects it to a temporary file

#!/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

The above script works perfectly and logs all the data continuously. However I need to write the redirection (/tmp/size.txt) too many times making the script looks clumsy. I was able to do it earlier but somehow it is not working as the syntax looks incorrect.

Can i please get some help here so i don't need to repeat the redirection and can be handled in just one line.

Thank you

Upvotes: 1

Views: 921

Answers (1)

anubhava
anubhava

Reputation: 786091

Move >> /tmp/size.txt after done and remove it from inside:

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

Upvotes: 1

Related Questions