1、编辑一个login.sh程序,模拟登陆
[root@hadoop102 ~]# vim test1
read -p "请输入姓名:" name
read -p "请输入密码:" pass
if(($name=="root" && $pass==123456))
then
echo "登录成功"
else
echo "登录失败"
fi
2、写一个firewall.sh程序,实现一次性的打开或者关闭防火墙和NetworkManager
- 当在命令行输入 firewall.sh start 时, 是开启firewalld和NetworkManager服务
- 当在命令行输入 firewall.sh stop 时, 是关闭firewalld和NetworkManager服务
- 当在命令行输入 firewall.sh status 时, 是查看firewalld和NetworkManager服务的状态
[root@hadoop102 ~]# vim test2
read -p "请输入你的操作:" result
case $result in
"firewall.sh start")
echo "开启firewalld服务"
systemctl start firewalld
echo "开启NetworkManager服务"
systemctl start NetworkManager
;;
"firewall.sh stop")
echo "关闭NetworkManager服务"
systemctl stop firewalld
echo "关闭NetworkManager服务"
systemctl stop NetworkManager
;;
"firewall.sh status")
echo "查看firewalld服务"
systemctl status firewalld
echo "查看NetworkManager服务"
systemctl status NetworkManager
;;
esac`
3、写一个脚本test.sh ,判断 “/home” 是不是一个目录,如果是:输出 this is a directory,如果不是,输出this is not a directory
[root@hadoop102 ~]# vim test3
if [ -d /home ]
then
echo "this is a directory"
else
echo "this is not a directory"
fi
4、在一个脚本里,使用read命令 读取year和month。然后输出year年month月有多少天(分别用if和case实现)
[root@hadoop102 ~]# vim test4
read -p "请输入年份:" year
read -p "请输入月份:" month
if((month==2))
then
if(((year%4==0 && year%100!=0) || year%400==0 ))
then
echo $"年"$"月有28天"
else
echo $"年"$"月有30天"
fi
elif((month==1||3||5||7||8||10||12))
then
echo $"年"$"月有31天"
elif((month==4||6||9||11))
then
echo $"年"$"月有31天"
else
echo "你的输入有误"
fi
[root@hadoop102 ~]# vim test4
read -p "请输入年份:" year
read -p "请输入月份:" month
case $month in
2)
if(((year%4==0 && year%100!=0) || year%400==0))
then
echo $year"年"$month"月有28天"
else
echo $year"年"$month"月有30天"
fi
;;
1 | 3 | 5 | 7 | 8 | 10 | 12 )
echo $year"年"$month"月有31天"
;;
4 | 6 | 9 | 11 )
echo $year"年"$month"月有30天"
;;
*)
echo "输入有误"
esac
5、使用循环和read命令,给一个数组names,赋值10个元素,如果有个元素是exit。就直接退出循环(提示:break)
[root@hadoop102 ~]# vim test5
names=()
for ((i=1;i<=10;i++))
do
echo "请输入第"$i"个数"
read num
if((num=="exit"))
then
break
fi
names[i-1]=$num
done
echo ${names[*]}
6、写一个脚本,计算1~100的所有偶数的和
[root@hadoop102 ~]# vim test6
count=0
for((i=1;i<=100;i++))
do
if((i%2!=0))
then
count=$[count + i ]
fi
done
echo $count
7、写一个脚本,打印出1000以内的所有素数
[root@hadoop102 ~]# vim test7
for((i=1;i<=1000;i++))
do
if((i==1 || i==2 ))
then
echo $i
fi
for((j=2;j<i;j++))
do
if((i%j==0))
then
break
fi
if((j==i-1))
then
echo $i
fi
done
done
8、定义一个cal函数,可以在命令行上调用此函数,灵活计算任意三个数的乘积
eg:
]# cal 2 3 4
24
[root@hadoop102 ~]# source test8
fun1(){
result=$[ $1 * $2 * $3 ]
echo $result
return $result
}
fun1 2 3 4 #加载资源(source test8)后可实现控制台输入 如:fun1 5 6 7 8 9
9、测试shift指令可以左移参数的功能
[root@hadoop102 ~]# vim test9
until [ "$1" == "" ]
do
echo "第一个数为:$1"
shift
done
10、利用shift的功能,计算命令行上的任何个参数之和
[root@hadoop102 ~]# vim test10
count=1
until [ "$1" == "" ]
do
ji=$[ $count + $1 ]
shift
done
echo "和为:$count"