一直在用bash,但是卻只是一知半解,這篇是學習Bash 腳本教程的學習筆記,算是查漏補缺。
基本語法
command [ arg1 ... [ argN ]]
ls -i
ls是命令,-l是參數。
type
type
命令可以顯示一個命令是不是內置命令:
bash-3.2$ type npm
npm is /Users/versions/node/v14.16.1/bin/npm
變量
export
用戶創建的變量僅可用於當前 Shell,子 Shell 默認讀取不到父 Shell 定義的變量。爲了把變量傳遞給子 Shell,需要使用export命令。這樣輸出的變量,對於子 Shell 來說就是環境變量。
export Foo=foo
bar=bar
node
> process.env.Foo
'foo'
> process.env.bar
// 讀不到
字符串處理
- 獲得字符串長度:
a="1234455"
echo ${#a}
- 獲取子字符串,語法爲
${varname:offset:length}
str="hello"
echo ${str:2} # llo
算術表達式
兩個小括號裏面可以計算算數表達式
a=2
b=4
(($a + $b))
echo $(($a + $b))
- 進制轉換
echo $((0xff)) # 16進制
echo $((2#1011101)) # 二進制
echo 4((077)) # 八進制
算數表達式也可以用到條件判斷裏面:
a=3
if (($a > 2))
then
echo 'yes'
fi
條件判斷
語法:
if commands; then
commands
[elif commands; then
commands...]
[else
commands]
fi
注意: 中括號中引用變量名要用雙引號引起來
- 字符串比較
string1=string2;
if [ "$string1" = "string2" ]
then
echo "== $string1"
fi
- 數字比較
if ((3 > 2)); then
echo "true"
fi
- 正則比較
INT=-5
if [[ "$INT" =~ ^-?[0-9]+$ ]]; then
echo "INT is an integer."
exit 0
else
echo "INT is not an integer." >&2
exit 1
fi
循環
for i in {1..4}
do
echo $i
done
其中{1..4}
表示一個連續的序列,這個要和[1-4]
區分開,這個是在匹配,如正則表達式中用到的
ls hello[1-4].txt
函數
定義一個函數很簡單:
fn(){
}
調用的時候可以傳參fn foo
,在函數體內可以引用這些參數:
$1~$9:函數的第一個到第9個的參數。
\(0:函數所在的腳本名。
\)#:函數的參數總數。
下面是一個例子;如果直接調用hello
,會要求輸入名字再打印,如果傳入參數hello name
,則直接打印。
hello() {
if (($# > 0))
then
echo "Hello $1";
else
echo "what's your name";
read name;
echo "Hello $name"
fi
}