4、流控、循环
if
if 条件测试
then
内容
elif 条件测试
then
内容
elif 条件测试
then
内容
else #注意此处没有then 加then是错误语法
内容
fi
case
case 变量 in
模式一)#加不加引号一样,匹配空字符时要加""
命令序列
;;#分号一定不能少
模式二)
命令序列
;;
模式三)
命令序列
;;
*)
无匹配的默认序列
esac
示例:删除用户
#!/bin/bash
#del user
#by dengwei
#date 2021.4.21
read -p "Please input a user: " user
id $user&>/dev/null
if [ $? -ne 0 ]; then
echo "username is not exist"
exit -1
fi
read -p "Are sure?[y]" action
case "$action" in
y|Y|yes|YES)
userdel -r $user
echo "success"
;;
"*")
echo "exit"
esac
简单测试
#!/bin/bash
#del user
#by dengwei
#date 2021.4.21
read -p "Please input a user: " user
read -p "Are sure?[y]" action
case "$action" in
y|Y|yes|YES)
echo "success"
;;
"*")
echo "exit"
esac
for(对文件逐行处理最好用while)
for 变量 in {取值列表}
do
命令序列
done
for 变量 #后面什么都不加表示获取所有参数
do
命令序列
done
示例:
#!/bin/bash
ip=www.baidu.com
for i in {1..100}
do
{//将循环放在后台加快速度{}&
ping -c1 $ip&>/dev/null
if [ $? -eq 0 ]; then
echo "$ip"
fi
}&
done
wait#等待前面所有后台结束
echo "finish"
{
}&#将循环放在后台加快速度{}&
IFS=“\n”按行分割 IFS修改分隔符
#!/bin/bash
IFS="\n"
if [ $# -eq 0 ];then
echo "please input a file"
exit -1
fi
if [ ! -f $1 ];then
echo "$1 isn't a file"
exit -1
fi
for i in `cat $1`
do
echo "$i"
done
while
while 条件测试
do
循环体
done#<file/$1等会输入重定向
条件测试为真时执行
until
until 条件测试
do
循环体
done
条件测试为假时执行
break(同C语言)
continue(同C语言)
exit(同C语言)
shift
将位置变量往左移动, shift n往左移动n个,并减少参数总共个数
./1.sh 1 2 3
脚本内部shift 1 一次,参数变为 2 3分别对应$1 $2