關於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’? 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM