Printing a specific line from bash_history

Often I want to archive specific commands out of my immediate bash history to a batch script that I can run later.
Unfortunately I could find no way of redirecting !# (where # is the bash history line I wish to save, e.g. !58 executes line 58) to a file. There is the "colon p" option - where !#:p will print the command instead executing it, but I could not redirect or pipe that output either.

So I added this one-liner to a bin directory in my path:


#!/bin/bash
cat $HISTFILE | sed -n "$1p"


I call it getHistLine. So now to save line 58 to a batch script I can just type:
getHistLine 58 >> myBatchScript.sh

To save a range of lines I can type
getHistLine 50,58 >> myBatchScript.sh

Comments

Popular Posts