shell是什麼
Shell 是一個用C語言編寫的程序,它是用戶使用Linux的橋樑。
Shell既是一種命令語言,又是一種程序設計語言,這個應用程序提供了一個界面,用戶通過這個界面訪問操作系統內核的服務。
shell腳本是什麼
shell是爲shell編寫的腳本程序。
Bash是大多數Linux系統默認的Shell。
#! 告訴系統其後路徑所指定的程序即是解釋此腳本文件的Shell程序。 如: #!/bin/bash
運行方法
第一種: chmod +x ./test.sh #使腳本具有執行 ./test.sh #執行腳本 第二種: /bin/sh test.sh #運行解釋器
變量
使用變量
your_name="qinjx" echo $your_name echo ${your_name} #花括號可加可不加
設置只讀變量
myUrl="http://www.w3cschool.cc" readonly myUrl
- 刪除變量 unset
字符串
獲取長度
string="abcd" echo ${#string} #輸出 長度4
提取字符串
echo ${string:1:4}
查找index
string="runoob is a great company" echo `expr index "$string" is` # 輸出 8
數組
定義
array_name=(value0 value1 value2 value3)
讀取
valuen=${array_name[n]} echo ${array_name[@]} #獲取所有元素
獲取長度
length=${#array_name[@]} lengthn=${#array_name[n]}
腳本參數
獲取參數
腳本內獲取參數的格式爲:$n $# 傳遞到腳本的參數個數 $* 以一個單字符串顯示所有向腳本傳遞的參數。 如"$*"用「"」括起來的情況、以"$1 $2 … $n"的形式輸出所有參數。 如"$@"用「"」括起來的情況、以"$1" "$2" … "$n" 的形式輸出所有參數。
運算符
原生bash不支持簡單的數學運算,但是可以通過其他命令來實現,例如 awk 和 expr,expr 最常用。
expr 是一款表達式計算工具,使用它能完成表達式的求值。例如,兩個數相加(注意使用的是反引號 ` 而不是單引號 ‘):#!/bin/bash val=`expr 2 + 2` echo "兩數之和爲 : $val"
echo
。。。沒啥說的,就是顯示
printf
printf "%-10s %-8s %-4.2f\n" 郭靖 男 66.1234
if
if condition1
then
command1
elif condition2
then
command2
else
commandN
fi
for
for var in item1 item2 ... itemN
do
command1
command2
...
commandN
done
while
while condition
do
command
done
函數
- 使用
funWithReturn(){
echo "這個函數會對輸入的兩個數字進行相加運算..."
echo "輸入第一個數字: "
read aNum
echo "輸入第二個數字: "
read anotherNum
echo "兩個數字分別爲 $aNum 和 $anotherNum !"
return $(($aNum+$anotherNum))
}
funWithReturn
echo "輸入的兩個數字之和爲 $? !"
#函數返回值在調用該函數後通過 $? 來獲得
- 函數參數
funWithParam(){
echo "第一個參數爲 $1 !"
echo "第二個參數爲 $2 !"
echo "第十個參數爲 $10 !"
echo "第十個參數爲 ${10} !"
echo "第十一個參數爲 ${11} !"
echo "參數總數有 $# 個!"
echo "作爲一個字符串輸出所有參數 $* !"
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73
包含外部腳本,以便獨立使用
source 或者 .
#使用 . 號來引用test1.sh 文件 . ./test1.sh # 或者使用以下包含文件代碼 # source ./test1.sh