Use Shell scripts to automatically back up source files before vi, cp, and mv.

Source: Internet
Author: User

The following script backs up all source files to be edited to the/bak directory, and keeps all paths unchanged, such as vi/etc/hosts, copy/etc/hosts to/bak/etc/hosts.

# Cat/sh/vii

#! /Usr/bin/bash

# Check whether the source file exists before performing the backup operation

If [-f "$1"]; then

# Create a function to enable any key to continue

# If stty raw is not recognized on your machine, replace the raw in the two parts of the function with cbreak.

Get_char ()

{

SAVEDSTTY = 'stty-G'

Stty-echo

Stty raw

Dd if =/dev/tty bs = 1 count = 1 2>/dev/null

Stty-raw

Stty echo

Stty $ SAVEDSTTY

}

# Create the backup root path/bak and grant everyone the write permission

If [! -D "/bak"]; then

Mkdir/bak

Chmod a + w/bak

Fi

# Determine the path of the target file and create it so that everyone has the write permission on any newly created level directory.

Echo $1 | grep "/">/dev/null

If ["'echo $? '"=" 0 "]; then

Cd $ {1% /*}

Fi

Pwdnow = 'pwd'

Path =/bak $ {pwdnow}

# Echo $ path

If [! -D "$ path"]; then

Mkdir-p $ path

Patha =$ {pwdnow #/}

Chmod-R a + w/bak/$ {patha % /*}

Fi

# Copying the target file

Datenow = 'date + % Y % m % d'

Timenow = 'date + % H % M % s'

/Usr/bin/cp $1 $ {path}/$ {1 # */}. $ {datenow}. $ {timenow}

Echo "Target file \" $1 \"

Has been copied to $ {path}/$ {1 # */}. $ {datenow}. $ {timenow }"

Echo "Now going to \" vi $1 \ ", Press any key to continue ..."

Char = 'get _ char'

Fi

# Call the vi command

Vi $1

Call scripts

# Chmod a + x/sh/vii

#/Sh/vii/etc/passwd

You can add/sh to the path variable for convenience.

Likewise, it is best to back up the target file when the cp/mv command is involved to avoid accidental overwrite.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.