What's the quickest way to add text to a file from the command line?

  • Occasionally I have a thought that I want to write into a file while I am at the terminal. I would want these notes all in the same file, just listed one after the other. I would also like a date / time tag on each one.

    Is it possible to do this without having to open the file each time? Can I just enter it into the terminal and have it appended to the file each time with a command or script?

    I am using GNU BASH.

  • Kyle Jones

    Kyle Jones Correct answer

    9 years ago

    Write yourself a shell script called "n". Put this in it:

    date >> $notefile
    emacs $notefile -f end-of-buffer

    I recommend this instead of cat >> notefile because:

    1. One day you'll be in such a hurry that you'll fumblefinger the >> and type > instead and blow away your file.
    2. Emacs starts in five one-hundredths of a second on my Mac Mini. It takes a tenth of a second to start on a ten year old Celeron-based system I have sitting around. If you can't wait that long to start typing, then you're already a machine and don't need to take notes. :)

    If you insist on avoiding a text editor, use a shell function:

    n () { date >> /home/me/notefile; cat >> /home/me/notefile; }

    which should work in all shells claiming Bourne shell compatibility.

    How does the `n` function write to the file? Don't you mean something like a `echo "$*"` rather than UUOC? How does it incorporate the date/time tag?

    Not quite useless. It reads from stdin, which is where the user will be typing their note. I did forget the datestamp, though.

    I don't necessarily agree about the UUOC, but you have you point back for the date...

    +1 nice defensive coding *and* rationale against the inevitable typo.

    Kyle, you obviously don't have a 90MB `.emacs.d`. Yikes, I need to clean that up.

    Esepcially good because it doesn't force neophytes to memorize that >> means append, because if they had to type that in over and over, soon the day would come when they typed > instead. Oops!

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM