1. 程式人生 > >linux 下 shell命令 && || 區別

linux 下 shell命令 && || 區別

 在執行某個 命令時,有時需要依賴前面的命令是否執行成功。假如你想通過ssh命令複製很多資料檔案到另外的機器後,刪除所有源有檔案,所以在刪除源有檔案之前首先要確定複製是不是執行成功。只要執行復製成功才可以刪除,否則後果......
一、&& 1.格式    command1 && command2 2.含義    &&左邊的command1執行成功(返回0表示成功)後,&&右邊的command2才能被執行。 3.例項 (1)當把檔案sql.txt複製一份為sql.bak.txt成功,然後顯示副本sql.bak.txt [
[email protected]
shell]# cp sql.txt sql.bak.txt && cat sql.bak.txt  Database        Size(MB)        Date Created -------------------------------------------- GOSOUTH         2244            12/11/97 TRISUD          5632            8/9/99 (2 rows affected)
(2)當檔案facebook.txt經過排序並儲存在facebook.txt.sorted被執行成功,列印facebook.txt.sorted 檔案 sort facebook.txt > facebook.txt.sorted &&  lp facebook.txt.sorted

二、||
1.格式    command1 || command2 2.含義    如果||左邊的command1執行失敗(返回1表示失敗),就執行&&右邊的command2。 3.例項 (1)列印1111.txt的第一列內容,若執行不成功則執行顯示facebook.txt的內容 [
[email protected]
shell]# awk '{print $1}' 1111.txt || cat facebook.txt    awk: cmd. line:1: fatal: cannot open file `1111.txt' for reading (No such file or directory) google 110 5000 baidu 100 5000 guge 50 3000 sohu 100 4500 (2)當列印1111.txt的第一列內容得命令被成功執行,則不執行列印facebook.txt的命令 [
[email protected]
shell]# awk '{print $1}' facebook.txt || cat facebook.txt google baidu guge sohu
三、() 如果想執行幾個命令,則需要用命令分隔符分號隔開每個命令,並使用圓括號()把所有命令組合起來。 結合||和&&可以實現複雜的功能。 1.格式(command1;command2;command3;...) 2.例項 (1)使用多個命令,如果sort命令執行成功,先將排序後的檔案備份到/root/backup/目錄下,然後再列印 sort facebook.txt > facebook.txt.sorted && (cp facebook.txt.sorted /root/backup/facebook.txt.sorted;lp facebook.txt.sorted) (2)列印facebook.txt檔案失敗就發郵件告知root使用者,並關機 lp facebook.txt.sorted ||(echo "It was not submitted succuessfully" | mail root;init 0)