bash極簡教程


今天看到消息,來自大神阮一峰的《bash腳本教程》開源發布了,
我也借此機會來總結個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 '{print $1}' | 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 {1..5}; 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腳本還有個好處就就是跨平台。
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

如果邏輯太復雜時,需要使用perl或者python

bash腳本雖然支持所有的條件控制,但是很多基本操作總是感覺很別扭,
比如整數,浮點數,字符串的比較,數組的操作,hash的操作,set的操作,正則表達式的匹配等。
所以我一般只有簡單的命令和if/else/for才寫bash,再復雜的邏輯就使用perl或者python。

參考

阮一峰的《bash腳本教程》: https://wangdoc.com/bash/index.html
開源地址:https://github.com/wangdoc/bash-tutorial

linux的命令和腳本參考,也可以參考小站:http://www.linux6.com/
開源地址:https://github.com/itech001/linux6


免責聲明!

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



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