Skip to content

Instantly share code, notes, and snippets.

@markgraf
Created April 29, 2020 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markgraf/d7974c23f335124f5b3c74ee5afa7008 to your computer and use it in GitHub Desktop.
Save markgraf/d7974c23f335124f5b3c74ee5afa7008 to your computer and use it in GitHub Desktop.
Quickly turn your history into a shell script.

More often than not, I typed a couple of commands and realized that I will need those more often.

So I redirected my history into a file history > somefile.sh and edited that, removing line numbers and timestamps. Tedious work that can be automated with the following shell-function for bash.

qs () {
  # Quickly turns a shell-session into a script.
  # --------------------------------------------
  # The function will
  # - delete history number
  # - delete history timestamp
  # - write all commands after "###" to the end of your history to  somefile.sh
  #
  # Usage:
  # - Start your session with "###<enter>".
  # - Type your commands.
  # - Run qs somefilename.sh.
  # - Edit somefile.sh to your liking.
  local filename="$1"
  history \
    | sed 's/^[[:blank:]]\+[0-9]\+[[:blank:]]*//' \
    | sed -E 's/^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} //' \
    | sed '/^###/{h;d};H;$!d;x' \
    | sed '$d' \
    > ${filename:?No filename given}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment