bash grep 判斷 bash極簡教程

2021-10-14 13:08:45 字數 2314 閱讀 7621

今天看到訊息,來自大神阮一峰的《bash指令碼教程》開源發布了,

我也藉此機會來總結個bash極簡教程

本文是乙個更加簡化的《bash極簡教程》,告訴你什麼時候需要使用bash,最常用的bash語法及關鍵字使用。

在linux系統裡,我們經常會遇到一些操作,不能使用單個命令完成,但是可以使用多個命令組合來完成。如果可以使用命令的組合完成的沒有必要寫指令碼。 命令的組合可以使用;,&&, {} 和 |, 例如:

apt-get update; apt-get upgrade

apt-get update && apt-get upgrade

cat tmp.txt | cut -d ' ' -f 2

mkdir -p aaa/bbb/ccc && touch aaa/bbb/ccc/ddd.txt

以下這些命令經常組合在一起使用,學會了就可以裝13了,就可以初步感受到linux的魅力。

ls, find, xargs, awk,cat, grep,sed, cut, sort, uniq, tr

find . -name '*.pyc' -exec rm -rf {} ;

find dir1 dir2 dir3 dir4 -type d -exec cp header.shtml {} ;

find xargstest/ -name 'file??' | sort | xargs wc -l

cat countryinfo.txt | grep -v "^#" >countryinfo-n.txt

cut -f 3 -d, list.txt | awk '' | sort | uniq

終極大招,命令列裡使用if/else/for,這個要是用熟了,那你就是大神了,工作會有飛一樣的感覺,跟玩差不多。。。

if [ -f "/usr/bin/wine" ]; then export winearch=win32; fi

[ -f "/usr/bin/wine" ] && export winearch=win32

[ -f ~/sample.txt ] && echo 「file exists.」 || touch ~/sample.txt

ps aux | grep some_proces[s] > /tmp/test.txt ; if [ $? -eq 0 ]; then echo 1; else echo 0; fi

for i in ; do command-here; done

for i in /etc/*.conf; do cp $i /backup; done

for num in `seq 1 1 1000`; do touch $num-file.txt; done

需要重複執行且邏輯簡單。 bash指令碼還有個好處就就是跨平台。 bash裡常用的條件控制if/else/for:

# 寫法一

if test -e /tmp/foo.txt ; then

echo "found foo.txt"

fi# 寫法二

if [ -e /tmp/foo.txt ] ; then

echo "found foo.txt"

fi# 寫法三

if [[ -e /tmp/foo.txt ]] ; then

echo "found foo.txt"

fi

最常用的判斷檔案,字串等。。。

[ -e file ]:如果 file 存在,則為true

[ -s file ]:如果 file 存在且其長度大於零,則為true。

[ string ]:如果string不為空(長度大於0),則判斷為真。

[ integer1 -eq integer2 ]:如果integer1等於integer2,則為true。

for迴圈的使用,使用bash指令碼的最主要的理由:

for i in word1 word2 word3; do

echo $i

done

for i in *.png; do

ls -l $i

done

bash指令碼雖然支援所有的條件控制,但是很多基本操作總是感覺很彆扭,

比如整數,浮點數,字串的比較,陣列的操作,hash的操作,set的操作,正規表示式的匹配等。

所以我一般只有簡單的命令和if/else/for才寫bash,再複雜的邏輯就使用perl或者python。

bash之判斷型別

1.4.3.1判斷型別 算術判斷 注意一點 中左邊 必須要有空格,然後再到比較值,後邊的比較值也要有空格再到 eq 表示 判斷是否相等 示例如下 2 eq 2 echo 輸出 0 2 ne 2 表示不等 3 gt 1 表示 於 3 ge 3 表示 於等於 3 lt 4 表示 於 3 le 3 表示 ...

BASH 判斷命令是否成功執行

問題 需要在成功執行某個命令之後執行乙個命令。比如,你需要進入某個目錄,刪除其中所有的檔案,但是如果 cd命令失敗,你就不去執行刪除的動作 比如許可權不允許,或者你把目錄的名字輸入錯誤 解決方案 可以使用 cd命令的返回值 並結合if 語句進行判斷。cd mytmp if then rm fi 討論...

bash 的判斷檔案操作語句

unix shell 程式設計 1 e file file存在 f file file存在並且是普通檔案 r file file有讀許可權 s file file存在且不為空 w file file寫許可權 x file file有執行許可權 a file 如果 file 存在則為真。b file ...