目錄
shell腳本賦權
chmod 777 file.sh
1、帶索引的 for 循環
#!/bin/bash
for ((i=0;i<10;i++));do
echo $i,$(date)
done
2、for循環遍歷數組
#!/bin/bash
arr1=(20 21 23 24 25)
arr2=(a b c d e f g)
for i in ${arr1[*]};do
echo -e $i "\c"
done
echo
for i in ${arr2[@]};do
echo -e $i "\c"
done
echo
# -e:轉義,"\c":不換行
# for循環遍歷數組
# ; 爲條件結束符
# do 相當於左花括號
# done 相當於右花括號
3、for循環遍歷字符串
#!/bin/bash
str="hello world!"
for ((i=0;i<${#str};i++));do
echo ${str:$i:1}
done
4、for循環遍歷參數
#!/bin/bash
for i in $*;do
echo $i
done
5、if、elif、else和if test
arr1=(20 21 23 24 25)
arr2=(a b c d e f g)
if ((${arr1[0]}==$[10]));then
echo "arr[0]=10"
elif test ${arr1[0]} -eq $[20];then
echo "arr[0]=20"
elif test ${arr1[0]} -eq 30;then
echo "arr[0]=30"
else
echo "arr[0]=-1"
fi
# then 相當於左花括號,然後沒有右花括號
# fi爲if的字母倒序,表示if語句執行結束
6、while循環和break
# while循環
n=20
while (($n>10));do
echo -e $n "\c"
((n--))
done
echo
# while true和break
while true;do
echo -e "$n" "\c"
((n--))
if ((n==0));then
echo "break"
break
fi
done
7、shell 函數
# 聲明函數
sum(){
echo "This is a method!"
n=0
for i in 1 2 3;do
((n+=i))
done
return $n
}
# 執行函數sum
sum
# $? 表示函數返回值
echo $?