流程控制
- if
[root@localhost test]# cat demo12.sh
#!/bin/bash
SSH_TEST_DIR="/opt/test22/"
if [ ! -d $SSH_TEST_DIR ]
then
mkdir -p $SSH_TEST_DIR
fi
[root@localhost test]# sh demo12.sh
[root@localhost test]# ls -d /opt/test22
/opt/test22
#!/bin/bash
ping -c 3 -i 0.2 -W 3 $1 &>/dev/null
if [ $? -eq 0 ];then
echo "Host $1 is up."
else
echo "Host $1 is down."
fi
[root@localhost test]# cat demo14.sh
#!/bin/bash
read -p "输入你的成绩(0-100):" SCORE
if [ $SCORE -ge 85 ] && [ $SCORE -le 100 ];then
echo "$SCORE 学霸666"
elif [ $SCORE -ge 70 ] && [ $SCORE -le 84 ];then
echo "$SCORE 一般般,还有加油啊"
elif [ $SCORE -ge 60 ] && [ $SCORE -le 69 ];then
echo "$SCORE 才及格"
else
echo "$SCORE 辣"
fi
- for
[root@localhost test]# cat user.txt
jake
tom
bob
[root@localhost test]# cat demo15.sh
#!/bin/bash
USER_LIST=$(cat /opt/test/user.txt)
for USER in $USER_LIST
do
id $USER &>/dev/null
if [ $? -ne 0 ];then
useradd $USER
echo "123456" | passwd --stdin $USER
fi
done
[root@localhost test]# sh demo15.sh
更改用户 jake 的密码 。
passwd:所有的身份验证令牌已经成功更新。
更改用户 tom 的密码 。
passwd:所有的身份验证令牌已经成功更新。
更改用户 bob 的密码 。
passwd:所有的身份验证令牌已经成功更新。
[root@localhost test]# id tom
uid=1003(tom) gid=1003(tom) 组=1003(tom)
[root@localhost test]# id bob
uid=1004(bob) gid=1004(bob) 组=1004(bob)
[root@localhost test]# id jake
uid=1002(jake) gid=1002(jake) 组=1002(jake)
- whil
[root@localhost test]# cat demo17.sh
#!/bin/bash
i=1
while [ $i -le 18 ]
do
let i++
done
echo $i
- break 跳出循环
- continue中断执行后面的语句跳到下一层循环
[root@localhost test]# cat demo18.sh
#!/bin/bash
while read -p "输入累加数字(0表示结束):" num
do
[ $num -eq 0 ] && break
SUM=$[SUM+num]
done
echo "sum=$SUM"
[root@localhost test]# . demo18.sh
输入累加数字(0表示结束):1
输入累加数字(0表示结束):2
输入累加数字(0表示结束):3
输入累加数字(0表示结束):0
sum=6
- exit
退出脚本,可以指定返回的状态值默认的返回值是0
[root@localhost test]# cat demo19.sh
#!/bin/bash
if [ $# -ne 2 ];then
echo "$0 输入两个参数"
exit 10
fi
expr $1 + $2
[root@localhost test]# sh demo19.sh
demo19.sh 输入两个参数
[root@localhost test]# echo $?
10
shell 函数
[root@localhost test]# function adder {
> echo $[$1+$2]
> }
[root@localhost test]# adder 1 2
3
- case
[root@localhost test]# cat /etc/init.d/myprog
#! /bin/bash
# chkconfig: 2345 10 95 //设置chkconfig 运行级别 启动顺序 关闭顺序
# description: A test service script for MyProg. 描述
case "$1" in
start)
echo "启动myprog服务.. .."
sleep 86400 &
;;
stop)
echo "停止myprog服务.. .."
pkill -9 sleep ;;
status)
pgrep -l sleep &> /dev/nu1l && echo "运行中" || echo "未运行"
;;
restart)
$0 stop
$0 start
;;
*)
echo $"用法:$0 {start | stop| restart | status}"
exit 1
esac
[root@localhost test]# chkconfig --add myprog //添加系统服务
[root@localhost test]# chkconfig --list myprog //查看系统服务
注:该输出结果只显示 SysV 服务,并不包含
原生 systemd 服务。SysV 配置数据
可能被原生 systemd 配置覆盖。
要列出 systemd 服务,请执行 'systemctl list-unit-files'。
查看在具体 target 启用的服务请执行
'systemctl list-dependencies [target]'。
myprog 0:关 1:关 2:开 3:开 4:开 5:开 6:关