Use shell script to implement automatic backup of source files before VI/CP/MV

Source: Internet
Author: User
Tags chmod continue mkdir backup

The following script backs up all the source files to be edited into the/bak directory, and all path locations remain unchanged, such as Vii/etc/hosts, and the/etc/hosts is copied to/bak/etc/hosts.

# CAT/SH/VII

#!/usr/bin/bash

#判断源文件是否存在, exist to perform a backup operation

If [F "$"];then

#创建函数, you can implement any key to continue

#如果你的机器上不认stty Raw, then replace the two occurrences of raw in 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

}

#创建备份的根路径/bak, and let everyone have write permission

if [!-d "/bak"];then

Mkdir/bak

chmod A+w/bak

Fi

#判断目标文件所处的路径并创建, let everyone have write permission on a newly created directory of any level

echo $ | 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

#复制目标文件

datenow= ' Date +%y%m%d '

timenow= ' Date +%h%m%s '

/USR/BIN/CP $ ${path}/${1##*/}.${datenow}.${timenow}

echo "Target" File "$"

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

echo "Now going to" VI $ ", press any key to continue ..."

Char= ' Get_char '

Fi

#调用vi命令

VI $

Calling script

# chmod A+X/SH/VII

#/SH/VII/ETC/PASSWD

You can add/sh to the path variable, which is more convenient.

Similarly, it is best to back up the target file when it comes to CP/MV commands to avoid accidental overwriting.

Related Article

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.