Shell脚本实践
1. 脚本判断命令输出是否为空
(1)判断字符串为空
if [ "$str" = "" ]
if [ x"$str" = x ]
if [ -z "$str" ] (-n 为⾮空)
注意:都要代双引号,否则有些命令会报错,养成好习惯吧!
2.输⼊y/n
可以使⽤判断符号进⾏数据的判断,如检查某变量是否为空 [ -z $SHELL ],需要注意的是中括号(“[]”)内的组件必须以空格隔开。有以下脚本:
#!/bin/bash
read -p "input you choice(y/n):" choice
[ "$choice" == "y" ] || [ "$choice" == "Y" ] && echo "OK,continue" && exit 0
[ "$choice" == "n" ] || [ "$choice" == "N" ] && echo "Oh,interrupt!" && exit 0
echo "I don't know what is your choice" && exit 0
#! /bin/sh
shell最简单脚本echo "Is it morning? Please answer yes or no."
read YES_OR_NO
if [ "$YES_OR_NO" = "yes" ]; then
echo "Good morning!"
elif [ "$YES_OR_NO" = "no" ]; then
echo "Good afternoon!"
else
echo "Sorry, $YES_OR_NO not recognized. Enter yes or no."
exit 1
fi
exit 0
(3)while条件循环
和C语⾔类似。⽐如⼀个验证密码的脚本:
#! /bin/sh
echo "Enter password:"
read TRY
while [ "$TRY" != "secret" ]; do
echo "Sorry, try again"
read TRY
done
下⾯的例⼦通过算术运算控制循环的次数:
#! /bin/sh
COUNTER=1
while [ "$COUNTER" -lt 10 ]; do
echo "Here we go again"
COUNTER=$(($COUNTER+1))
done
(3)case 和 while 结合
#!/bin/bash
while : :表⽰真,⼀直循环
do 要循环执⾏的命令
echo -n "enter any number [1-5]:" 输⼊序号1-5
read nu 设置read的变量
case $nu in 进⾏选择,输⼊的要是1-5的数字
1|2|3|4|5)
echo "enter anumber 1 and 5" 就循环这⼀⾏,让你不停的输⼊1-5
;;
*) 如果输⼊的不是1-5的数字
echo -n "wrong number, continue (y/n?:)" 询问你是否继续
read con 设置read的变量
case $con in 进⾏选择,看是不是y|yes|Y|YES这⼏个
y|yes|Y|YES)
continue 如果是,那么就跳过,让你重新输⼊,如果不是
;;
*) 那么就执⾏这个break退出循环
break
;;
esac esac done
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论