0

So I'm writing a Python script that passes different parameters to a Unix command and I need all of the command outputs to be saved to the same file.

However the only way I know is to re-write the file. Does anyone know how to append a file in Shell Script

Say my Unix command is:

Foo

and my operators are:

bar
bar1
bar2

The Unix command would be:

foo bar > output.txt
foo bar1 > output.txt
foo bar2 > output.txt

The contents of output.txt would only be "foo bar2"

Does anyone know how to append the file so all three command outputs will be in the output file?

jubilatious1
  • 3,195
  • 8
  • 17
Verudux
  • 11

4 Answers4

3

Each one of your three separate commands empties the output.txt file before writing new data to it. This is why the file ends up only containing the data from the last command executed.

To redirect a set of commands to a file, you could use

{
    foo bar
    foo bar1
    foo bar2
} >output.txt

or, on a single line,

{ foo bar; foo bar1; foo bar2; } >output.txt

The curly braces defines a compound command. The redirection after the terminating } redirects all output of the compound command as a whole.

Since we use >, the file will be emptied before the output of the compound command is written to the output.txt file. If you want to append to the file, use >> instead.


Another alternative:

for operand in bar bar1 bar2; do
    foo "$operand"
done >output.txt

or, in a shell that has brace expansions,

for operand in bar{,1,2}; do
    foo "$operand"
done >output.txt

Here, the for loop is a compound command that may be redirected just like the { ...; } compond command above.

Again, if you want to retain the original contents of output.txt and only append to the file, use >> rather than > for the redirection.

Kusalananda
  • 333,661
1

In the Unix shell the >> (greater greater) symbol can be used to append to a file, e.g.

command >> file.txt
1

In the last two commands, you need to use >> instead of >, which appends the content instead of completely replacing it, as > does.

schaiba
  • 7,631
1

So i literally found this minutes after posting.

The answer is to replace the > with >>

With the syntax of:

foo bar >> output.txt
foo bar1 >> output.txt
foo bar2 >> output.txt

A single > is to write to file.

A double > is to append to a file.

Verudux
  • 11