shell 中的for迴圈while迴圈和case語句
阿新 • • 發佈:2019-01-04
迴圈語句
1)for 迴圈
第一種語法格式:
for((初始化變數值;結束迴圈條件;迴圈控制語句))
do
迴圈體
done
eg.
#!/bin/sh
sum=0
for ((i=0;i<10;i++))
do
echo $i
sum=$[ $sum + i ]
done
echo $sum
第二種語法格式:
for 變數 in 值1 值2 ...值N
do
迴圈體
done
eg.
#!/bin/sh
for MONTH in Jan Feb Mar Apr May Jun July Aug Sep Oct Nov Dec
do
echo $MONTH
done
#!/bin/sh
for file in `/bin/ls ~`;
do
echo $file;
done
2)while 迴圈
第一種語法格式:
while [ condition #迴圈條件 ]
do
#statements
#【迴圈體】
#【迴圈控制】
done
eg.
#!/bin/sh
i=1
while [ $i -le 10 ]
do
sum=$((sum+i))
i=$[ i + 1 ]
done
echo $sum
第二種語法格式:
while read -r line
do
#【迴圈體】
done
eg.
#!/bin/sh
#Read /ect/sysconfig/network-scripts/ifcfg-eh0 and print out
FILE=/ect/sysconfig/network-scripts/ifcfg-eh0
while read -r line
do
echo $line
done < $FILE
3)case 類似於java中的 swich case
第一種語法格式:
#!/bin/sh
echo "input from: one two three"
read input
case $input in
one) echo "your input is one"
;;
two) echo "your input is two"
;;
three) echo "your input is three"
;;
*) echo your input is $input
esac
第二種語法格式:
#!/bin/sh
echo "input from :one two three ....."
read input
case $input in
one | two) echo "your input is one or two"
;;
three | four) echo "your input is three or four "
;;
five) echo "your input is five"
;;
*) echo your input is $input
esac
1)for 迴圈
第一種語法格式:
for((初始化變數值;結束迴圈條件;迴圈控制語句))
do
迴圈體
done
eg.
#!/bin/sh
sum=0
for ((i=0;i<10;i++))
do
echo $i
sum=$[ $sum + i ]
done
echo $sum
第二種語法格式:
for 變數 in 值1 值2 ...值N
do
迴圈體
done
eg.
#!/bin/sh
for MONTH in Jan Feb Mar Apr May Jun July Aug Sep Oct Nov Dec
do
echo $MONTH
done
#!/bin/sh
for file in `/bin/ls ~`;
do
echo $file;
done
2)while 迴圈
第一種語法格式:
while [ condition #迴圈條件 ]
do
#statements
#【迴圈體】
#【迴圈控制】
done
eg.
#!/bin/sh
i=1
while [ $i -le 10 ]
do
sum=$((sum+i))
i=$[ i + 1 ]
done
echo $sum
第二種語法格式:
while read -r line
do
#【迴圈體】
done
eg.
#!/bin/sh
#Read /ect/sysconfig/network-scripts/ifcfg-eh0 and print out
FILE=/ect/sysconfig/network-scripts/ifcfg-eh0
while read -r line
do
echo $line
done < $FILE
3)case 類似於java中的 swich case
第一種語法格式:
#!/bin/sh
echo "input from: one two three"
read input
case $input in
one) echo "your input is one"
;;
two) echo "your input is two"
;;
three) echo "your input is three"
;;
*) echo your input is $input
esac
第二種語法格式:
#!/bin/sh
echo "input from :one two three ....."
read input
case $input in
one | two) echo "your input is one or two"
;;
three | four) echo "your input is three or four "
;;
five) echo "your input is five"
;;
*) echo your input is $input
esac