模式匹配case
case的语法结构
case 变量 in
模式1)
命令序列1
;;
模式2)
命令序列2
;;
模式3)
命令序列3
;;
*)
无匹配后的命令序列
esac
脚本中交互式实现
判断用户输入的字符串,
如果用户输入的字符串为start,就在/tmp下创建一个start文件;
如果用户输入的为stop,那么就删除/tmp/start文件;
如果用户输入的为restart,那么就先删除/tmp/start文件,然后创建一个start1文件;
如果用户输入其他的字符串,就输出一个帮助信息:脚本名 Usage:{start|stop|restart}
read -p "请输入字符串:" strings
case $strings in
start)
touch /tmp/start
;;
stop)
rm -rf /tmp/start
;;
restart)
if [ -e /tmp/start ]
then
rm -rf /tmp/start
else
touch /tmp/start1
fi
;;
*)
echo "$0 Usage:{start|stop|restart}"
esac
1.超市卖水果
你输入苹果,显示 苹果 5元每斤
你输入香蕉 ,显示 香蕉 3元每斤
你输入橘子,显示 橘子 3元每斤
如果你输入的不是苹果 香蕉 橘子 就提示只能查询 苹果 香蕉 橘子
#!/bin/bash
read -p "输入要查询价格的水果名:" aa
case $aa in
apple)
echo "apple 5元每斤";;
banana)
echo "banana 3元每斤";;
orange)
echo "orange 3元每斤";;
*)
echo "Usage :{apple|banana|orange}"
esac
按需安装下列软件,cherrytree,dhcp,sshd
函数
完成特定功能的代码段(块)
在shell中定义函数可以使用代码模块化,便于复用代码
函数必须先定义才可以使用
一、定义函数
方法一:
函数名() {
函数要实现的功能代码
}
方法二:
function 函数名 {
函数要实现的功能代码
}
二、函数的调用
函数名
1.函数外的参数能被函数调用
#!/bin/bash
a=123
num_1() {
echo $a
}
num_1
2.函数内的参数也能被函数调用
#!/bin/bash
num_1() {
a=123
}
num_1
echo $a
3.使用local来隔离变量,使参数只能在函数内调用
#!/bin/bash
num_1() {
local a=123
echo “in num_1”
echo $a
}
num_1
echo "out of num_1"
echo $a
[root@today tmp]# bash f.sh
in num_1
123
out of num_1
#!/bin/bash
#
start() {
touch /tmp/start
}
stop() {
rm -rf /tmp/start
}
read -p "请输入字符串:" strings
if [ $strings == "start" ]
then
start
elif [ $strings == "stop" ]
then
stop
elif [ $strings == "restart" ]
then
stop
start
else
echo "$0 Usage:{start|stop|restart}"
fi