Shell腳本中的語法與C語言類似
一、shell的一些基本瞭解
1.shell腳本的後綴名爲“ .sh”
2.shell文本以 #!/bin/bash 開頭。#!是一個約定的標記,它告訴這個系統這個腳本需要什麼解釋器來執行。
3.shell文本通用的兩種執行方式:
(1) /bin/bash test.sh
(2)對test.sh增加可執行權限 chmod u+x test.sh , 然後 ./test.sh 即可執行
二、shell的基本語法:
1.條件測試
(1)常見的測試命令包含test 或 [
(2)測試類型不同用的命令不同
—–>整數測試:-eq (==) , -ne(!=) , -lt(<) , -gt(>) , -le(<=) ,-ge(>=)
—–>字符串測試:== != -z(字符串爲空) -n(字符串不爲空)
—–>文件測試: -d (目錄文件) -f(普通文件) -b(塊設備) -c(字符文件)
2.測試用例
#!/bin/bash
//定義函數
function intAdd()
{
let data=$1+$2
echo $data
}
//三種死循環
#until false
#do
# echo "hello world"
#done
#while true
#do
# echo "hello"
#done
#for ((;;))
#do
# echo "hello"
#done
#i=0
#until [ $i -ge 10 ] //當i的值不大於等於10爲真
#do
# echo "hello $i"
# let i++
#done
#i=0
#while [ $i -le 5 ]
#do
# echo "hello $i"
# ((i++))
# #let i++
#done
#for i in {a..e} {1..5}
#do
# echo "hello $i"
#done
#for i in {a..z}
#do
# echo "hello $i"
#done
#for i in {1..20}
#do
# echo "hello $i"
#done
//循環語句
#for (( i=0; i<=10; i++ ))
#do
# echo "hello $i"
#done
//類似switch ... case 語句
#case $1 in
# 'start' )
# echo "start ... done"
# ;;
# 'stop' )
# echo "stop ... done"
# ;;
# 'result' )
# echo "result ... done"
# ;;
# 'status' )
# echo "status ... done"
# ;;
# * )
# echo "default"
# ;;
#esac
//懶邏輯
#printf "data:"
#read data
#[ $data -eq 100 ] && echo "yes1"
#[ $data -eq 100 ] || { echo "yes2"
#}
#printf "data:"
#read data
#[ $data -eq 100 ] && echo "yes"
#[ $data -eq 100 ] && { echo "yes"
#}
//不能進行空操作,":"表示真
#printf "data:"
#read data
#if [ $data -eq 100 ];then
# :
#else
# echo "AAAAAA"
#fi
#printf " file name:"
#read filename
#
#if grep -Eq '222' "$filename";then
# echo "yes"
#else
# echo "no"
#fi
//循環嵌套
#printf "data:"
#read data
#if [ $data -lt 100 ];then
# if [ $data -eq 50 ];then
# echo "data is -eq 50"
# elif [ $data -lt 50 ];then
# echo "data is -lt 50"
# else
# echo "data -gt 50 and -lt 100"
# fi
#else
# echo "data is great than 100"
#fi
//if語句
#printf "string:"
#read mystring
#if [ "X$mystring" == "Xhello" ];then
# echo "get hello"
#fi
//
#printf "string:"
#read mystring
#if [ "X$mystring" == "Xhello" ]
#then
# echo "get hello"
#fi
//多條語言測試
#printf "data1:"
#read data1
#printf "data2:"
#read data2
#[ $data1 -eq 100 -o $data2 -eq 200 ]
#echo $?
#printf "data1:"
#read data1
#printf "data2:"
#read data2
#[ $data1 -eq 100 -a $data2 -eq 200 ]
#echo $?
#read mysqtring
#[ !"X$string"=="Xhello" ]
#echo $?
//測試文件
#[ -c /dev/tty ] #字符設備
#echo $?
#[ -b /dev/sda ] #塊設備
#echo $?
#[ -f /test.sh ] #普通文件
#echo $?
#[ -d / ] #目錄
#echo $?
//測試字符串,添加X防止對空串判斷出錯
#read mystring
#[ "X$mystring" == "hello" ]
#echo $?
//測試字符串
#read mystring
#[ $mystring == "hello" ]
#echo $?
#[ $mystring != "hello" ]
#echo $?
#[ -z $mystring ] #是否爲空串
#echo $?
#[ -n $mystring ] #是否爲非空串
#echo $?
//測試整數
#read myint
#test $myint -eq 100
#echo $?
#
#[ $myint -ne 100 ]
#echo $?
#[ $myint -lt 100 ]
#echo $?
#[ $myint -gt 100 ]
#echo $?
#[ $myint -le 100 ]
#echo $?
#[ $myint -ge 100 ]
#echo $?