Create Script from Bash History

The script program (bsdutils) will output the whole terminal output to a file. This can be helpful for logging and creating scripts out of history.

The approach here is to output the command history to a file and then manipulate the file a bit to get what we want.

history 3 >

This will output the last 3 commands to Note that the actual history command will become the most recent event in history, and will be output in the file. This can be edited out manually or using this command:

head -n -1 > && mv{.tmp,}

The head command will remove the last line and update the file. The last step is to remove the line numbers from the beginning of the lines. Do that with sed:

sed -i "s/^ *[0-9]* //g"

Finally, ensure is executable with:

chmod +x

The file could be tweaked to include the shebang #!/bin/bash and make sure there are no extra white spaces in the file. These commands could all be packaged together in their own script in order to easily create scripts from history. An example usage could be:

hist2script 4