3

I want to create an alias to append a dated note to a file. (The use case I want to reproduce : Sebastian Daschner - How to do effective note taking as developer.

So far I was able to append the date, but I cannot figure out a way to append both the date and the note from user input.

Usage

append-to-file 'my text'

Expected result in file.txt

2021-08-30 : some previous text
2021-09-01 : my text

The alias I have written so far

alias append-to-file='tee -a file.txt <<< $(echo $(date -I) :)'

2 Answers2

4

You can do this with a little script. One way could be:

#!/bin/bash
echo "$(date -I) : $@" >> file.txt
tail -n 1 file.txt

The $@ variable stands for anything you entered at the command line. The tail command will echo the last line of the file to the screen.

Save this script in your ~/bin or in your .local/bin directory as append-to-file. Create the directory if it does not exist. Next time you log in, either of these directories will be included in your PATH. You then can enter the command anytime. What you enter will be saved in a file file.txt in the current working directory.

vanadium
  • 97,564
3

If you want something that you can pass a text message to as an argument, you should be looking at a shell function rather than an alias.

You could consider using the ts (timestamp) utility from package moreutils:

append-to-file () { printf '%s\n' "$*" | ts '%Y-%m-%d :' >> /path/to/myfile.txt ; }

If ts is not an option, you can insert text into the format string of the date command - but you'd need to be careful about % characters:

append-to-file () { msg="$*"; date "+%Y-%m-%d : ${msg//%/%%}" >> /path/to/myfile.txt ; }

or (thanks to @bac0n) perhaps safer, use the bash printf function's own time formatting capabilities - there's no need to replace %s in this method, since the message is being passed as a string argument rather than embedded in the format string:

append-to-file () { printf '%(%Y-%m-%d)T : %s\n' -1 "$*" >> /path/to/myfile.txt ; }

If you want it echoed to the terminal as well, replace >> with | tee -a

steeldriver
  • 142,475