Write the output of multiple sequential commands to a text file

I try to Check the latest Firefox and want to get all hashes in one TXT file.

What I try to do is:

sha1sum firefox.tar.gz > sha.txt

and I try also:

md5sum firefox.tar.gz > sha.txt | sha1sum firefox.tar.gz > sha.txt | sha512sum firefox.tar.gz > sha.txt 

but only the last in this case the sha512 is printed to the sha.txt.

What am I doing wrong? Please can someone out there help me with this?


As others have already pointed out the difference between > (overwrite) and >> (append) redirection operators, i am going to give couple of solutions.

  1. You can use the command grouping {} feature of bash to send the output of all the commands in a single file :

    { sha1sum foo.txt ;sha512sum foo.txt ;md5sum foo.txt ;} >checksum.txt
    
  2. Alternately you can run the commands in a subshell () :

    ( sha1sum foo.txt ;sha512sum foo.txt ;md5sum foo.txt ) >checksum.txt
    

You need to use the append redirector >> instead of > for the subsequent commands e.g.

sha1sum zeromq-4.1.2.tar.gz > sha.txt
md5sum zeromq-4.1.2.tar.gz  >> sha.txt 
sha512sum zeromq-4.1.2.tar.gz >> sha.txt 

See the Appending Redirected Output section of the bash manual page (man bash).


The > redirector writes the command's output (stdout, not stderr - you use 2> for that) to the file specified after it. If it already exists, the file will get overwritten.

This behaviour is useful for the first of your commands: if there's an existing file, it should get deleted and replaced with the new one.

However, as you need to append all further outputs instead of replacing the previous ones, you need to use the append-redirector >>. This will create a file if it does not exist yet, but appends the redirected output to the file, if it already exists.


And please do not use the pipe | to write multiple commands in one line, which would redirect the first command's output (stdout) to the second command's input (stdin).

You can use the semicolon (;) to just tell bash to execute one command after the other, as if it was a script file. If a command fails (return code is not 0), the remaining commands still get executed.

Or you may chose the logic operators AND (&&) or OR (||):
If you use && to connect two commands, the second one will only be executed, if the first one succeeds (return code is 0). If it fails, none of the following commands will run.
The || however only runs the second command if the first one failed (return code is not 0)!

So in your case I would recommend you to use the semicolon:

md5sum firefox.tar.gz > sha.txt ; sha1sum firefox.tar.gz >> sha.txt ; sha512sum firefox.tar.gz >> sha.txt