- if 結(jié)構(gòu)
語句結(jié)構(gòu):
if 代表語句塊開始,fi代表語句塊結(jié)束。
if [condition] : then ...; fi
if [condition]: then ...;else ...; fi
if [conditon]: then ...;elif ...; fi
if [ -e test ];then echo exist;else echo not exist; fi 等價(jià)于 [ -e test ] &&echo exist||not exist
echo "1" && echo "2" || echo "3" && echo "4" || echo "5" ||echo "6"&& echo "7" && echo "8" || echo "9"
前面結(jié)果為真绍弟,則執(zhí)行&& 后面的先嬉,否則執(zhí)行|| 內(nèi)容
- for 循環(huán)
語句結(jié)構(gòu):
for((c1;c2;c3));do...done
for循環(huán)第一種使用方式, 定義變量捆交,根據(jù)數(shù)字判斷 示例1:for ((i=0;i<10;i++));do echo $i;done
for循環(huán)第二種方式,遍歷迭代序列中的內(nèi)容
示例1: array=(1 2 3 4 5)腐巢,for x in {x} ;done
示例2: for x in {x} ;done
- while 循環(huán)
語句結(jié)構(gòu):
i=0;while[ {i}; ((i++));done
當(dāng)while條件為真品追,則執(zhí)行do done里面的語句,否則不執(zhí)行do done中的語句
用while一行行讀取文件內(nèi)容
文檔1 內(nèi)容為a b c d
while read x; do echo ${x};done<1
">" 輸出重定向冯丙;將屏幕內(nèi)容重定向到指定文件中
"<" 輸入重定向肉瓦,將文檔1的內(nèi)容輸出給wile語句中 遭京,將1賦值給變量x
- 退出控制
return: 函數(shù)返回
exit:腳本退出
break:退出當(dāng)前循環(huán),默認(rèn)為1 示例:for f in * ;do echo
{f} ]; then break;fi;done
break 2 :退出兩層循環(huán)
continue: 跳過當(dāng)前的循環(huán)泞莉,進(jìn)入下一次循環(huán) for f in * ;do echo
{f} ];then echo ${f} is file ;else continue;fi;done
continue 2:跳到上層上層循環(huán)的下一次循環(huán)中
- Shell的運(yùn)行環(huán)境
bash 是一個(gè)進(jìn)程哪雕,bash下可以再重新啟動(dòng)一個(gè)shell,重新啟動(dòng)的shell為 子 shell鲫趁,原shell會(huì)復(fù)制自身給 子shell斯嚎,子 shell中的變量會(huì)隨著 子 shell的消亡而消失
() 子 shell 中云運(yùn)行 b=5 (b=1;echo
挨厚 小括號(hào)里面內(nèi)容在子shell中運(yùn)行
{} 當(dāng)前shell中執(zhí)行 { b=11;echo
獲取當(dāng)前腳本的執(zhí)行id echo $$
& 后臺(tái)執(zhí)行
$! 運(yùn)行在后臺(tái)的最后一個(gè)作業(yè)的PID(進(jìn)程ID)
創(chuàng)建子shell并退出子shell : bash命令疫剃、 exit命令
啟動(dòng)暫停任務(wù)钉疫,sleep 50 按下鍵盤Ctrl +z,處于暫停狀態(tài)巢价,bg 3 繼續(xù)執(zhí)行任務(wù)牲阁,fg 3 將其展示(3是任務(wù)的編號(hào))
-
[圖片上傳失敗...(image-797169-1542868835727)]
image.png
- shell 環(huán)境變量
打開 .bash_profile 設(shè)置環(huán)境變量后
配置執(zhí)行sh腳本的路徑 PATH=
引用原有的PATH,添加帶配置的腳本文件路徑到原有PATH上壤躲,記住有跟個(gè)":”)
退出保存bash_profile
執(zhí)行source ~/.bash_profile 將更改的環(huán)境變量文件生效
- shell 輸入輸出
輸出重定向 > echo "hello " >1
輸出追加重定向>> echo "hello +++ hello " >>1
文本搜索 grep "hello" test.txt
-i 忽略大小寫 cat test.txt | grep -i "hello"
-o 只顯示匹配到內(nèi)容 cat test.txt | grep -io "hello"
“.” 匹配任意一個(gè)字符 echo absc |grep -o 'b.'
“” 匹配所有內(nèi)容 echo absc |grep -o 'b.'
- 常用命令&快捷鍵:
快速查找之前的命令:由下往上查找咨油,ctrl + r
歷史操作過的命令查找:history
查看文件: cat
創(chuàng)建文檔并編輯: vim 文件名 點(diǎn)擊鍵盤i ,輸入內(nèi)容柒爵,點(diǎn)擊esc :wq! 強(qiáng)制保存退出
向鍵盤讀入命令:read 示例: read a;echo
{a}
查看進(jìn)程(PID): ps
查看任務(wù)狀態(tài):jobs
將所有隱藏文件都展示出來:ls -al
顯示文件:ls
更改文件權(quán)限: chmod
文本搜索命令:grep 搭配正則表達(dá)式使用
-
訪問一個(gè)頁面 :curl
curl http://www.baidu.com/s?wd=mp3 | less 翻頁查看curl -s http://www.baidu.com/s?wd=mp3 | grep -o "結(jié)果約[0-9]" [0-9]匹配數(shù)字
curl -s http://www.baidu.com/s?wd=mp3 | grep -o "結(jié)果約[0-9,]* "
curl -s http://www.baidu.com/s?wd=mp3 | grep -o "結(jié)果約[0-9,]" |grep -o "[0-9,]"
“ | grep -o "結(jié)果約[0-9,]" |grep -o "[0-9,]" ” 通過grep 不斷把前一項(xiàng)內(nèi)容向后過濾役电,直至獲取到想要的內(nèi)容