在bash腳本的第一行要寫上#!/bin/bash來告訴系統該腳本是bash腳本
這一行在Linux中被稱為shebang
#!/bin/bash
1、變量
在bash腳本中聲明變量與其他語言類似,而且不用聲明變量的類型,直接賦值就可以生效,可以接受字符串、數字等變量類型
示例:
str="hello world"
上面這行代碼創建了一個名為str的變量,并給它賦值為"hello world"
使用的時候在變量名前加上$進行調用
Example:
echo $str # hello world
2、數組
數組是一組數據的集合,在bash腳本中對數組的大小沒有限制,
下標同樣從0開始
下面示例的方法可以創建數組:
示例:
array[0] = val
array[1] = val
array[2] = val #方式一
array=([2]=val [0]=val [1]=val) #方式二
array=(val val val) #方式三
顯示數組的第一個元素
${array[0]}
查看數組包含的個數
${#array[@]}
Bash 像如下示例支持三元運算操作
${varname:-word} # 如果varname存在且不為null,則返回varname的值,否則返回word
${varname:=word} # 如果varname存在且不為null,則返回varname的值,否則將word賦值給varname
${varname:+word} # 如果varname存在且不為null,則返回word的值, 否則返回null
3、字符串操作
${variable#pattern} # 如果變量內容從頭開始的數據符合“pattern”,則將符合的最短數據刪除
${variable##pattern} # 如果變量內容從頭開始的數據符合“pattern”,則將符合的最長數據刪除
${variable%pattern} # 如果變量內容從尾向前的數據符合“pattern”,則將符合的最短數據刪除
${variable%%pattern} # 如果變量內容從尾向前的數據符合“pattern”,則將符合的最長數據刪除
${variable/pattern/string} # 如果變量內容符合“pattern”,則第一個匹配的字符串會被string替換
${variable//pattern/string} # 如果變量內容符合“pattern”,則所有匹配的字符串會被string替換
${#varname} # 返回變量的長度
4、函數/方法
與其他語言類似,方法是一組可復用操作的集合
functname() {
shell commands
}
示例:
!/bin/bash
function hello {
echo world!
}
hello
function say {
echo $1
}
say "hello world!"
當調用hello函數時,屏幕將輸出"world"
當調用say函數時,將在屏幕輸出傳入的第一個參數,在上例中就是"hello world!"
5、條件語句
與其他語言類似,也包含 if then else語句 和 case語句
if [ expression ]; then # [] 與 expression之間要有空格
will execute only if expression is true
else
will execute if expression is false
fi
case語句:
case expression in
pattern1 )
statements ;;
pattern2 )
statements ;;
...
esac
基本比較符:
statement1 && statement2 # statement1為true并且 statement2為true 則返回true
statement1 || statement2 # 至少一個為true,則返回true
str1=str2 # 比較兩個字符串是否相等
str1!=str2 # 比較兩個字符串是否不等
-n str1 # 判斷str1是否為 非null
-z str1 # 判斷str1是否為 null
-a file # file文件是否存在
-d file # file是否是一個文件夾
-f file # file文件是否是一個普通的非文件夾文件
-r file # 是否有可讀權限
-s file # 是否存在文件并且文件內容不為空
-w file # 是否有可寫權限
-x file # 是否有可執行權限
-N file # 文件是否在最后一次讀取時被修改
-O file # 是否是文件的所有者
-G file # 文件的所屬組是否與你屬于同一組
file1 -nt file2 # file1是否比file2新 (newer than)
file1 -ot file2 # file1是否比file2舊 (older than)
-lt # 小于
-le # 小于等于
-eq # 等于
-ge # 大于等于
-gt # 大于
-ne # 不等
6、循環
支持三種循環語句. for, while , until.
for 語句:
for x := 1 to 10 do
begin
statements
end
for name [in list]
do
statements that can use $name
done
for (( initialisation ; ending condition ; update ))
do
statements...
done
while 語句:
while condition; do
statements
done
until 語句:
until condition; do
statements
done
7、調試
有幾個簡單的調試命令可以在bash中使用 bash命令加上 -n 參數可以不執行腳本,只檢查語法錯誤 bash命令加上 -v 參數可以在腳本執行前把腳本內容顯示出來 bash命令加上 -x 參數可以在腳本執行過程中逐步顯示執行的腳本內容
bash -n scriptname
bash -v scriptname
bash -x scriptname