Search code examples
linuxbashputty

Quicker way of writing code to output file


Apologies if this has already been answered.

I have the following code that I am trying to make both more legible, less awkward looking, and easier to write.

#!/bin/bash
echo "'date' command output" >> Clauric.txt
echo "" >> Clauric.txt
echo date >> Clauric.txt
echo "" >> Clauric.txte
echo "'hostname' command output" >> Clauric.txt
echo "" >> Clauric.txt
echo hostname >> Clauric.txt
echo "" >> Clauric.txt
echo "'arch' command output" >> Clauric.txt
echo "" >> Clauric.txt
echo arch >> Clauric.txt
echo "" >> Clauric.txt
echo "'uname -a' command output" >> Clauric.txt
echo "" >> Clauric.txt
echo uname -a >> Clauric.txt

There are another 30 rows of similar commands that need to be outputted to a file, from which it is then read by another program.

Any help would be gratefully appreciated.


Solution

  • There are several ways to do this, but one of the simplest is to use a block:

    {
    echo "'date' command output"
    echo ""
    echo date
    echo ""
    echo "'hostname' command output"
    echo ""
    echo hostname
    echo ""
    echo "'arch' command output"
    echo ""
    echo arch
    echo ""
    echo "'uname -a' command output" 
    echo ""
    echo uname -a 
    } >> Clauric1.txt
    

    This way the output file is opened and closed only once, rather than on every line.

    By the way, when you say echo date it will not run the date program, it just displays those four characters ("date"). In this case you probably just need date without the echo (same with the other commands).