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.