13年学习linux练习shell脚本时写的几个简单例子。
1、 使用for循环、while循环、until循环计算100以内所有偶数的和
for循环:
#!/bin/sh
Sum=0
for i in `seq0 2 100` #也可用for iin $(seq 0 2 100)
#或者 for (( i=0;i<=100;i+=2 ))
do
let “Sum+=i”
done
echo “SUM=$Sum”
exit 0
while循环:
#!/bin/sh
Sum=0
i=0
while [ “$i” –le100 ]
do
let “Sum+=i”
let “i+=2”
done
echo “SUM=$Sum”
exit 0
until循环:
#!/bin/sh
Sum=0
i=0
until [ “$i” –gt100 ]
do
let “Sum+=i”
let “i+=2”
done
echo “SUM=$Sum”
exit 0
2、 通过循环实现从1开始叠加,直到和的结果大于2000为止(使用break循环控制符)
#!/bin/sh
Sum=0
for ((i=1;;i++)
do
let “Sum+=i”
if [ “$Sum” –gt 2000 ]
then
echo “i=$i”
echo “SUM=$Sum”
break
fi
done
exit 0
3、 找出100以内所有能被3整除的数,每行显示8个数,然后换行显示
#!/bin/sh
times=0 #循环次数
for i in $(seq1 100)
do
let “temp=i%3”
let “times++”
if [ “$temp” –eq 0 ]
then
printf “$i”
let “a=times%8”
if [ “$a” –eq 0 ]
then
printf “\n”
fi
fi
done
printf “\n”
4、 打印九九乘法表
#!/bin/sh
for ((i=1;i<=9;i++)
do
for (( j=1;j<=i;j++ ))
do
let “temp=i*j”
echo –n “$j*$i=$temp “
done
echo “”
done
exit 0
5、 显示颜色类型,并让用户选择(使用select结构)
#!/bin/sh
echo “What isyour favorite color?”
select colorin “red” “blue” “green” “white” “black”
do
break
done
echo “You haveselected $color.”
exit 0
6、 显示当前工作目录下的文件数和目录数
#!/bin/sh
Number()
{
let “dir_number=0”
let “file_number=0”
ls
echo “”
for file in `ls`
do
if [ -d “$file” ]
then
let “dir_number+=1”
elif [ -f “$file” ]
then
let “file_number+=1”
fi
done
echo “Thenumber of dirs is $dir_number.”
echo “Thenumber of files is $file_number.”
}
Number
exit 0
7、 打印下面图案:
*
**
***
****
*****
******
*******
********
*********
**********
<span style="color:#330033;">#!/bin/sh
for ((i=1;i<=10;i++ ))
do
for (( j=1;j<=i;j++ ))
do
echo –n “*”
done
printf “\n”
done
exit 0</span>
8、 输入一个整数,判断是否为完数(完数:一个数恰好等于它的因子之和,如6=1+2+3)
#!/bin/sh
sum=0
echo “Pleaseinput a number(>1):”
read number
for ((i=1;i<$number;i++ ))
do
let “temp=$number%i”
if [ “$temp” –eq 0 ]
then
let “sum+=i”
fi
done
if [ “$number”–eq “$sum” ]
then
echo“$number is Perfect number!”
else
echo “$number is not Perfect number!”
fi
exit 0
9、 输入一个数字(1-12),然后显示其对应的月份的英文(使用case结构)
#!/bin/sh
echo “Pleaseinput a month(1-12):”
read month
case “$month”in
1)
echo “The month is January!”;;
2)
echo “The month is February!”;;
3)
echo “The month is March!”;;
4)
echo “The month is April!”;;
5)
echo “The month is May!”;;
6)
echo “The month is June!”;;
7)
echo “The month is July!”;;
8)
echo “The month is Augest!”;;
9)
echo “The month is September!”;;
10)
echo “The month is October!”;;
11)
echo “The month is November!”;;
12)
echo “The month is December!”;;
*)
echo “The month is not in (1-12)!”;;
esac
exit 0
10、 输入一个年份,判断是否为闰年,判断条件:
(1) 能被4整除,但不能被100整除的年份都是闰年;
(2) 能被100整除,但又能被400整除的年份是闰年。
#!/bin/sh
echo “Pleaseinput a year:”
read year
#设置取余参数
let “n1=$year%4”
let “n2=$year%100”
let “n3=$year%400”
if [ ! “$n1” –eq0 ]
then
leap=0
elif [ ! “$n2”–eq 0 ]
then
leap=1
elif [ ! “$n3”–eq 0 ]
then
leap=0
else
leap=1
fi
if [ “$leap” –eq1 ]
then
echo “$year is a leap year!”
else
echo “$year is not a leap year!”
fi
exit 0