DEV Community

Raunak Ramakrishnan
Raunak Ramakrishnan

Posted on • Updated on

Bash function to add TILs from the command line

Here's a snippet I use in my .bashrc file to quickly write down and review TILs (Today I learned):

TIL_FILE="$HOME/my-notes-repo/til.md"
til () 
{ 
    # checks if the function has been called without any argument
    if [[ -z $1 ]]; then
        # opens the file in my editor, setting the cursor to the last line
        # useful to review latest entries or to write a longer entry
        vim + "$TIL_FILE";
    else
        # adds a line with today's date, a TAB and all arguments supplied ("$@")
        echo -e "- $( date '+%F' ):\t$@" >> "$TIL_FILE";
    fi
}
Enter fullscreen mode Exit fullscreen mode

How to use:

  • til to open the file. I use this to review what I learned today or if I need to write a longer, multiline entry
  • til CONTENT to append a line to the file
    • e.g til grep --line-buffered to immediately print especially when tailing files will add this: - 2020-05-23: grep --line-buffered to immediately print especially when tailing files

Explanation on the function

In case you missed the comments in the function, here's an explanation of what the various lines do:

  • if [[ -z $1 ]]; checks if the function has been called without any arguments
  • vim + "$TIL_FILE" opens the file in vim (my preferred editor), setting the cursor to the last line of the file.
  • echo -e "- $tdate:\t$@" >> "$TIL_FILE"; adds a line with today's date, a TAB and all arguments supplied ("$@") to til

Top comments (1)

Collapse
 
moopet profile image
Ben Sinclair

That's neat.

I might suggest using the EDITOR variable to pick up the user's preferred editor, and fall back to good ol' Vim if it's not set:

${EDITOR:-vim} + "$TIL_FILE"