9

Create Script from Bash History

 3 years ago
source link: https://www.devdungeon.com/content/create-script-bash-history
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Create Script from Bash History

Submitted by NanoDano on Wed, 11/21/2012 - 11:04

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

Advertisement


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK