October 29, 2008

safe guard editor

If you are like me, or a very experienced admin, you will realize that while running servers in production, you are more likely prompt to modify configuration files on the fly.

Now, one advise I give to any junior administrator, is to first of all backup any files they wish to modify. Running the cp command before editing a file, could be an hassle, especially when we are in a hurry.

The following tip isn’t a Bash scripting lesson as you will see but merely a safe guard concept, every admin could adopt to prevent downtime and headaches :-).

Here is a little bash script that I usually set up on servers whenever I am prompted to modify configuration files on the fly.

[sourcecode language=‘bash’] #!/bin/bash stamp=$(date +%s) /bin/cp $1 $1.$stamp /bin/vi $1 echo “Would you like to delete $1.$stamp ?” read choice if [ “$choice” = “yes” ]; then rm -f $1.$stamp fi [/sourcecode]

As you can see the script is very basic and straight forward, whenever the script is called such as “./vis filenameA”, it will make a copy of filenameA to filenameA. + the number of elapsed seconds since 01/01/1970 … it then opens up the file in my favorite editor ‘vi’ and prompt me later on if I wish to delete the backup file…

Now, you could modify this file, add more check conditions, spice up things but the idea behind it, is to create the automatic backup of files when they are being edited.

Save this script in a file.. chmod +x thescript (let’s call it vis)

Move it into the /bin folder and create an alias (alias vi=“vis”)

There you go…from now on, whenever you edit a file, you shouldn’t fear if you make a mistake or delete any important variable options.

Cheers,