| 论坛注册| 加入收藏 | 设为首页| RSS
Google
您当前的位置:首页 > Linux频道 > Linux开发区 > SHELL

Shell脚本 实现vi/cp/mv前自动备份源文件

时间:2007-08-28 10:47:12  来源:Linux联盟收集整理  作者:
 

以下脚本把所有要编辑的源文件备份到/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联盟

来顶一下
近回首页
返回首页
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表
相关文章
栏目更新
栏目热门