以下脚本把所有要编辑的源文件备份到/bak目录下,并且所有的路径位置保持不变,比如vii /etc/hosts,则把/etc/hosts复制到/bak/etc/hosts。 TMxLinux联盟
# cat /sh/vii TMxLinux联盟
#!/usr/bin/bash TMxLinux联盟
#判断源文件是否存在,存在才执行备份操作 TMxLinux联盟
if [ -f "$1" ];then TMxLinux联盟
#创建函数,可实现任意键继续 TMxLinux联盟
#如果你的机器上不认stty raw那么把函数中两处出现的raw换成cbreak TMxLinux联盟
get_char() TMxLinux联盟
{ TMxLinux联盟
SAVEDSTTY=`stty -g` TMxLinux联盟
stty -echo TMxLinux联盟
stty raw TMxLinux联盟
dd if=/dev/tty bs=1 count=1 2> /dev/null TMxLinux联盟
stty -raw TMxLinux联盟
stty echo TMxLinux联盟
stty $SAVEDSTTY TMxLinux联盟
} TMxLinux联盟
#创建备份的根路径/bak,并让所有人具有写权限 TMxLinux联盟
if [ ! -d "/bak" ];then TMxLinux联盟
mkdir /bak TMxLinux联盟
chmod a+w /bak TMxLinux联盟
fi TMxLinux联盟
#判断目标文件所处的路径并创建,让所有人对新创建的任一级目录均具有写权限 TMxLinux联盟
echo $1 | grep "/" >/dev/null TMxLinux联盟
if [ "`echo $?`" = "0" ];then TMxLinux联盟
cd ${1%/*} TMxLinux联盟
fi TMxLinux联盟
pwdnow=`pwd` TMxLinux联盟
path=/bak${pwdnow} TMxLinux联盟
#echo $path TMxLinux联盟
if [ ! -d "$path" ];then TMxLinux联盟
mkdir -p $path TMxLinux联盟
patha=${pwdnow#/} TMxLinux联盟
chmod -R a+w /bak/${patha%%/*} TMxLinux联盟
fi TMxLinux联盟
#复制目标文件 TMxLinux联盟
datenow=`date +%Y%m%d` TMxLinux联盟
timenow=`date +%H%M%S` TMxLinux联盟
/usr/bin/cp $1 ${path}/${1##*/}.${datenow}.${timenow} TMxLinux联盟
echo "Target file \"$1\" TMxLinux联盟
has been copied to ${path}/${1##*/}.${datenow}.${timenow}" TMxLinux联盟
echo "Now going to \"vi $1\",Press any key to continue..." TMxLinux联盟
char=`get_char` TMxLinux联盟
fi TMxLinux联盟
#调用vi命令 TMxLinux联盟
vi $1 TMxLinux联盟
调用脚本 TMxLinux联盟
# chmod a+x /sh/vii TMxLinux联盟
# /sh/vii /etc/passwd TMxLinux联盟
你可以把/sh加入到PATH变量中,这样就更方便了。 TMxLinux联盟
同理,涉及cp/mv命令时最好也备份一下目标文件,以免被意外覆盖。 TMxLinux联盟