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 > script.sh
This will output the last 3 commands to script.sh. 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 script.sh > script.sh.tmp && mv script.sh{.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" script.sh
Finally, ensure script.sh is executable with:
chmod +x script.sh
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 myscript.sh