How to redirect the output of a command to an already existing file without deleting its contents?

10,274

Solution 1

If you want to append to a file you have to use >>.

So your examples would be

$ md5sum file >> checksums.txt

and

$ sha512sum file >> checksums.txt

Solution 2

Beside the >> operator to open the file in append mode as answered by @Thomas, an other option is to open the file with the > operator, but only once and leave it open for the two commands:

exec 3> checksums.txt

Would open (and truncate) the file on file descriptor 3, and then:

md5sum file1 >&3

Would write the md5sum of file1 in there.

md5sum file2 >&3

(when run from that same shell), would append the file2 md5sum.

Then, you can do:

exec 3>&-

to close that file descriptor. You can also do the same with stdout (file descriptor 1, the default for the > operator), by redirecting a whole command group:

{ md5sum file1; md5sum file2; } > checksums.txt

Or using a subshell instead of a command group:

(md5sum file1; md5sum file2) > checksums.txt
Share:
10,274

Related videos on Youtube

Carl Rojas
Author by

Carl Rojas

Updated on September 18, 2022

Comments

  • Carl Rojas
    Carl Rojas over 1 year

    I am making a backup of some files and am creating a checksum file, checksums.txt, to later check the integrity of my data. However pasting each checksum manually into the file is inconvenient since my backup consists of hundreds of files, so asking around I got the suggestion to simplify the process by redirecting the output to the checksum file:

    $ md5sum file > checksums.txt
    

    or

    $ sha512sum file > checksums.txt
    

    However doing this replaces the contents of the checksums.txt file with the checksum of, in this example, the file file; I would like, instead, to append the checksum of file to checksums.txt without deleting its contents. So my question is: how do I do this?

    Just one more thing. Since I am a basic user, try (only if possible) to make easy-to-follow suggestions.