Bash – How to save the last command to a file

bashcommand historyshell

When I am running my analyses using the bash shell, I often want to save the commands I've used that gave me good results to a file in the same directory (my "LOGBOOK", as its called) so that I can check what I did to get those results. So far this has meant me either copy.pasting the command from the terminal or pressing "up" modifying the command to an echo"my command" >> LOGBOOK, or other similar antics.

I found there was a history tool the other day, but I can't find a way of using it to get the previously executed command so that I can do something like getlast >> LOGBOOK.

Is there a nice easy way to do this. Alternatively, how do others deal with saving the commands for results they have?

Best Answer

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.]

Related Question