shell 陣列 迴圈
阿新 • • 發佈:2019-01-30
#!/bin/bash array=(1 2 3 4 5) #以括號括起為陣列 中間是空格 for num in "${array[@]}" #以這種for列印陣列 do echo $num done xxx[0]='a' #第二種定義陣列的方法 xxx[1]='b' xxx[2]='c' for ((i=0; i<${#xxx[@]};i++)); do # ${#xxx[@]} 返回陣列的大小 echo ${xxx[i]} #${xxx[$i]} ${xxx[${i}]} 這兩種都可以 通過下標列印陣列 陣列從0開始 done #對目錄處理的一些技巧 xxx=(`ls`) # ``這裡可以包含一些shell命令(~這個鍵) 這個配合管道命令是很強大的 grep sed for file in "${xxx[@]}" #用第二種for迴圈也是可以的 do echo $file done #sh相加字串是非常方便的 直接放到後面就可以了 #單引號和雙引號是有區別的 單引號只能放字串 雙引號裡面可以解釋變數 initPath='/a' secPath='/b' thrPath='c' path=${initPath}'/' path=${initPath}${secPath}'/'${thrPath} #對數字的支援可能就比較煩了 xxx=2 xx=${xxx}-1 echo $xx #輸出:2-1 echo $(($xxx-1)) #如果是數字運算 外面加上 $(( )) 才會得到正確的結果 let "x=xxx+(xx*2)" #let 相當於(()) 這個比較好用 echo $x x=$((xxx+(xx*2))) #2種方式相同 如果是數字處理可以不帶$ 字串必須要帶$ 或 ${} echo $x #declare 可以定義變數的屬性 declare -i i=1 #定義一個int的變數 declare -i sum=0 while ((i<10)); do #while迴圈 let sum+=i let ++i done echo $sum while read line; do echo $line break #shell是支援 break 和 countinue的 done #if 語句 判斷數字的寫法 [ ] 兩邊都要有空格 -ne 不相等的意思 這裡比較的是數字 所以 $(($filesNum-1))這個就要這樣寫 $((${filesNum}-1)) 都可以 if [ "$j" -ne "$(($i-1))" ]||[ "$j" -ne "$(($filesNum-1))" ]; then else fi #比較字串 是否相等 if [ "${initPath}" != "${buildPath}" ]; then elif [ command ]; then fi #判斷目錄是否存在 if [ ! -d "${buildPath}" ]; then mkdir $buildPath fi