How can I save the last command to a file?

If you are using bash, you can use the fc command to display your history in the way you want:

fc -ln -1

That will print out your last command. -l means list, -n means not to prefix lines with command numbers and -1 says to show just the last command. If the whitespace at the start of the line (only the first line on multi-line commands) is bothersome, you can get rid of that easily enough with sed. Make that into a shell function, and you have a solution as requested (getlast >> LOGBOOK):

getlast() {
    fc -ln "$1" "$1" | sed '1s/^[[:space:]]*//'
}

That should function as you have asked in your question.

I have added a slight variation by adding "$1" "$1" to the fc command. This will allow you to say, for example, getlast mycommand to print out the last command line invoking mycommand, so if you forgot to save before running another command, you can still easily save the last instance of a command. If you do not pass an argument to getlast (i.e. invoke fc as fc -ln "" "", it prints out just the last command only).

[Note: Answer edited to account for @Bram's comment and the issue mentioned in @glenn jackman's answer.]


One problem with @camh's answer is if you have a command that spans multiple lines, it only shows the first line:

$ echo "one
> two
> three"
one
two
three

$ fc -lnr | head -1
         echo "one

Try this:

$ alias getlast='fc -nl $((HISTCMD - 1))'

$ echo "one
> two
> three"
one
two
three

$ getlast
         echo "one
two
three"

Instead of using the up arrow, you can use "!!" to refer to the previous command.

e.g.

$ some -long --command --difficulty="very hard to remember"
$ echo "!!" >> LOGBOOK

note: this does not quote the literal text