Selective Bash history

Often I want to keep a registry of some commands I have used. Yes, Bash history can take care of it. However, here I am more interested in keeping track of a some commands, not all of them. Also, I want to have a copy of the register of the commands inside the working directory.

One possible solution for that is to use the Bash builtin “fc“. I have created a function named “sc” for “save command” and add it to my .bashrc file:

sc() {
    dt=`date`
    echo "# ${dt}" >> history
    fc -ln "$1" "$1" | sed '1s/^[[:space:]]*//' >> history
}

First, “sc” function retrieve the date and store it into “dt” variable;

Next, the date is printed (appended) to a file named history. By doing that, it is possible to check when the command have been issued.

After that, “fc” command retrieve the last command and sed takes care of the extra spaces.

One example:

$ touch foobar
$ sc

$ cat history 
# Mon 09 Dec 2019 07:26:27 PM CET
touch foobar

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s