5、shell编程范例
•5.1 shell编程范例一
编程要求:
在系统上创建名称为/root/linux1.sh的文件,要求提供如下功能:
1、当运行/root/linux1.sh redhat 输出fedora
2、当运行/root/linux1.sh fedora输出redhat
3、当输入的参数为空或不是redhat和fedora时,错误输出:
“input error,please input redhat | fedora”
分析:
很显然这是一个条件判断执行输出的案例,因此可以选择if条件语句或case语句。
if语句写法:
vim /root/linux1.sh
#!/bin/bash
if [ “$1” = “redhat” ];then
echo “fedora”
elif [ “$1” = “fedora” ];then
echo “redhat”
else
echo “input error,please input redhat|fedora”>&2
case语句写法:
vim /root/linux1.sh
#!/bin/bash
case “$1” in
“redhat”)
echo “fedora”
;;
“fedora”)
echo “redhat”
;;
*)
echo “input error,please input redhat|fedora” >&2
•5.2 shell编程范例二
编程要求:创建一个脚本,名为/root/linux2.sh,此脚本能实现为系统基于文件批量创建用户,包含用户账号的文件为/root/user.txt,同时要满足:
1、该脚本执行将/root/user.txt作为唯一参数。
2、执行脚本时如果没有提供参数,将输出如下提示信息
Usage: /root/user.txt然后退出并返回相应的值
3、执行脚本时如果提供了一个不存在的文件名,将输出如下提示信息
Input file not found然后退出并返回相应的值
4、创建的用户登陆shell为/bin/false
5、该脚本不需要为用户设置密码
分析:条件判断用if或case语句,批量创建意味着重复执行多个不同的参数,用for循环。
脚本示例:
vim /root/linux2.sh vim /root/user.txt
#!/bin/bash
if [ -z“$1” ];then
echo “Usage:/root/user.txt”
exit 1
fi
if [ ! -f“$1” ];then
echo “Input file not found ”
exit 1
fi
for NAME in $(cat $1);do
useradd –s /bin/false $NAME
done