shell脚本练习题

1.输入字符,判断字符类型

#!/bin/bash
read -p "字符" word
case $word in
	[[:upper:]])
		echo "大写字母"
		;;
	[[:lower:]])
		echo "小写字母"
		;;
	[0-9])
		echo "数字"
		;;
esac

2输入年月,判断该月有多少天

#!/bin/bash
read -p "please input year:" years
read -p "please input month:" months
case $months in 
	1|3|5|7|8|10|12)
		echo 31
		;;
	2)
		if [ $((years%4)) -eq 0 -a $((years%100)) -ne 0 -o $((years%400)) -eq 0 ]
		then
			echo 29
		else
			echo 28
		fi
		;;
	4|6|9|11)
		echo 30
		;;
esac

3,使用循环求100-1000的水仙花数

#!/bin/bash
for i in `seq 100 1 999`
do
	((j=i/100))
	((k=i/10%10))
	((m=i%10))
	if [ $(((j**3)+(k**3)+(m**3))) -eq $i ]
	then 
		echo "$i是水仙花数"
	fi
done

注意:

seq是指令,要命令置换符 

4.稀疏数组求和

#!/bin/bash
arr=([1]=10 [2]=100 [3]=300)
for i in ${arr[*]}
do
	((sum+=i))
done
echo $sum

5.求家目录下普通文件和目录文件个数

用cd

#!/bin/bash
cd ~
for i in `ls `
do
	if [ -d $i ]
	then
		((j++))
	elif [ -f $i ]
	then
		((k++))
	fi
done
echo "家目录有$j个目录文件"
echo "家目录有$k个普通文件"

不用cd,给文件名加路径 

#!/bin/bash
dir_num=0
file_num=0
for filename in `ls ~`
do
	if [ -d /home/ubuntu/$filename ]
	then
		((dir_num++))
	elif [ -f /home/ubuntu/$filename ]
	then
		((file_num++))
	fi
done
echo $dir_num
echo $file_num

 

注意: 

for in语句条件变量不用加$

6.冒泡排序

#!/bin/bash
arr=(1 0 8 4 9 5)
len=${#arr[*]}
for i in `seq 0 1 $((len-1))`
do
	for j in `seq 0 1 $((len-i-2))`
	do 
		((k=j+1))
		if [ $((arr[j])) -gt $((arr[k])) ]
		then
			((temp=arr[j]))
			((arr[j]=arr[j+1]))
			((arr[j+1]=temp))
		fi
	done
done
echo ${arr[*]}
#!/bin/bash
arr=(1 0 8 4 9 5)
len=${#arr[*]}
for ((i=1;i

7.成绩评级

#!/bin/bash
read -p "please input  the sore of student:" sore
if [ $sore -gt 100 ]
then
	echo "iliclt input"
else
	case $sore in
		9?|1??)
			echo 'A'
			;;
		8?)
			echo 'B'
			;;
		7?)
			echo 'C'
			;;
		6?)
			echo 'D'
			;;
		*)
			echo 'F'
	esac
fi

你可能感兴趣的:(linux,bash)