关于linux命令 cp,rm,mv执行时是否询问的问题,不同用户有不同的别名设置

三种命令的详细参考以下连接

http://c.biancheng.net/view/746.html

http://c.biancheng.net/view/744.html

http://c.biancheng.net/view/749.html

个人在不使用任何选项执行cp命令的时候,如果目标文件已经存在,有时会询问是否覆盖,而有时不会询问。

感到比较困惑,特意调查了一下。原来是因为执行用户的原因

当使用普通用于执行时不会询问,而使用超级用户root执行时会询问,这是因为两者别名的设置不同,如下所示

普通用户

[vagrant@localhost test1]$ alias
alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto'
alias grep='grep --color=auto'
alias l.='ls -d .* --color=auto'
alias ll='ls -l --color=auto'
alias ls='ls --color=auto'
alias vi='vim'
alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde'

超级用户别名

[vagrant@localhost test1]$ sudo su
[root@localhost test1]# alias
alias cp='cp -i'
alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto'
alias grep='grep --color=auto'
alias l.='ls -d .* --color=auto'
alias ll='ls -l --color=auto'
alias ls='ls --color=auto'
alias mv='mv -i'
alias rm='rm -i'
alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde'

可以看出,普通用户执行cp时,因为没有设置别名,所以默认是没有选项的,所以不会询问

而超级用户执行cp时,因为设置了别名  alias cp='cp -i'  ,所以默认是带 -i 选项的,所以会询问

同样,rm和mv命令也是如此

那么如何在使用root用户执行脚本中的cp命令不询问呢,可以在脚本中使用unalias命令删除别名

unalias cp

在代码中使用 alias 命令定义的别名只能在当前 Shell 进程中使用,在子进程和其它进程中都不能使用。当前 Shell 进程结束后,别名也随之消失。

同样,代码中使用 unalias 命令删除的别名也只能在当前 Shell 进程中使用,在子进程和其它进程中都不能使用。

测试

[root@localhost test1]# cp text2.txt text1.txt  //进程1,root用户
cp: overwrite ‘text1.txt’? y    //询问是否覆盖
[root@localhost test1]# bash   //创建进程2(子进程)
[root@localhost test1]# cp text2.txt text1.txt
cp: overwrite ‘text1.txt’? y
[root@localhost test1]# unalias cp   //删除别名
[root@localhost test1]# cp text2.txt text1.txt   //当前进程中没有询问,因为删除了别名
[root@localhost test1]# bash    //在子进程2中再创建子进程3
[root@localhost test1]# cp text2.txt text1.txt 
cp: overwrite ‘text1.txt’? y    //在子进程3中发生了询问,可见在父进程2中删除了别名在子进程3中无效
[root@localhost test1]# exit  //退出子进程3,返回子进程2
exit
[root@localhost test1]# cp text2.txt text1.txt
[root@localhost test1]# exit  //退出子进程2,返回进程1
exit
[root@localhost test1]# cp text2.txt text1.txt  //发生询问,可见在子进程中删除别名对父进程无效
cp: overwrite ‘text1.txt’? 

猜你喜欢

转载自www.cnblogs.com/gaoBlog/p/12335031.html