參考: https://seankross.com/the-unix-workbench/bash-programming.html
0x01 數學
expr 5 / 2
# 2
echo "5/2" | bc -l
# 2.50000000000000000000
0x02 變量
a=1
let a=$a+1
# 2
##### $() 命令行計算結果
files=$(ll|wc -l)
echo $files
# 365
##### 入參變量
#!/usr/local/bin/bash
echo "arguments: $@"
echo "arg1 : $1, arg2 : $2"
echo "arg count : $#"
# ./demo.sh aa bb
# arguments: aa bb
# arg1 : aa, arg2 : bb
# arg count : 2
##### 用戶輸入
read count
echo "Your input : $count"
# hello
# Your input: hello
##### 執行結果
true
echo $?
false
echo $?
# 0
# 1
##### 條件與或 && ||
##### 條件判斷
[[ 4 -gt 3 ]]
echo $?
# 0
Logical Flag | Meaning | Usage |
---|---|---|
-gt | 大於 | [[ $planets -gt 8 ]] |
-ge | 大於等於 | [[ $votes -ge 270 ]] |
-eq | 等於 (數字或字符串) | [[ $fingers -eq 10 ]] |
-ne | 不等於 | [[ $pages -ne 0 ]] |
-le | 小於等於 | [[ $candles -le 9 ]] |
-lt | 小於 | [[ $wives -lt 2 ]] |
-e | 文件存在 | [[ -e $taxes_2016 ]] |
-d | 目錄存在 | [[ -d $photos ]] |
-z | Length of String is Zero | [[ -z $name ]] |
-n | Length of String is Non-Zero | [[ -n $name ]] |
0x03 正則匹配
bash 不支持 \d \D \s \S \w \W
需要使用下面代替:
[[:digit:]],[^[:digit:]],[[:space:]],[^[:space:]], [_[:alnum:]], [^_[:alnum:]]
-
=~
正則匹配[[ $consonants =~ [aeiou] ]]
-
=
字符串相等[[ $password = "pegasus" ]]
-
!=
字符串不等[[ $fruit != "banana" ]]
-
!
邏輯取反[[ ! "apple" =~ ^b ]]
0x04 IF-ELSE
if [[ $1 -eq 4 ]]
then
echo "$1 is my favorite number"
elif [[ $1 -gt 3 ]]
then
echo "$1 is a great number"
else
echo "You entered: $1, not what I was looking for."
fi
0x05 數組
# 定義數組
fruits=(apple banana orange)
# 使用數組元素
echo ${fruits[0]}
fruits=(blood frogs lice flies sickness boils hail locusts darkness death)
# 打印所有元素
echo ${fruits[*]}
# Slice index:5 length:3
echo ${fruits[*]:5:3}
# 打印數組長度
echo ${#fruits[*]}
# 拼接新數組 +=
fruits+=(apple banana)
echo ${fruits[*]}
fruits+=(pear)
echo ${fruits[*]}
# blood frogs lice flies sickness boils hail locusts darkness death
# boils hail locusts
# 10
# blood frogs lice flies sickness boils hail locusts darkness death apple banana
# blood frogs lice flies sickness boils hail locusts darkness death apple banana pear
0x06 括號
可以生成字符串序列
echo {0..3}
# echo {a..z}{A..Z}
# 0 1 2 3
0x07 循環
for
for i in {0..3}
do
echo "i is equal to $i"
done
# i is equal to 0
# i is equal to 1
# i is equal to 2
# i is equal to 3
words=(sunny wendy randy jobs)
for a in ${words[*]}
do
echo "now word is : $a"
done
# now word is : sunny
# now word is : wendy
# now word is : randy
# now word is : jobs
files=$(ls)
for a in ${files[*]}
do
echo "當前目錄文件名 : $a"
done
while
count=3
while [[ $count -gt 0 ]]
do
echo "count now is $count"
let count=$count-1
done
# count now is 3
# count now is 2
# count now is 1
0x08 函數
function hello() {
echo "Hello"
}
# 這裏兩次調用函數
hello
hello
# Hello
# Hello
# 注意函數名後面的括號可以省掉
function hello2 {
echo "Nice to meet you $1"
}
hello2 小野花
# Nice to meet you 小野花
# 函數返回值
function do_sum {
# 防止污染全局變量 sum
local sum=0
for i in $@
do
let sum=$sum+$i
done
echo $sum
}
# 需要注意: 如何想從函數接收返回值, 需要使用 $()語法
t=$(do_sum {1..5})
echo "result is $t"
# result is 15
接下來看什麼?