[root@localhost ~]# set -o
allexport off
braceexpand off
emacs on
errexit off
errtrace off
functrace off
hashall on
histexpand on
history on
ignoreeof off
interactive-comments on
keyword off
monitor on
noclobber off
noexec off
noglob off
nolog off
notify off
nounset off
onecmd off
physical off
pipefail off
posix off
privileged off
verbose off
vi off
xtrace off
[root@localhost ~]# vim shell/error.sh
#!/bin/bash
echo "Hello World"
sssss
echo "Hello Linux"
[root@localhost ~]# chmod +x shell/error.sh
[root@localhost ~]# shell/error.sh
Hello World
shell/error.sh:行3: sssss: 未找到命令
Hello Linux
[root@localhost ~]# vim shell/error.sh
#!/bin/bash
set -e
echo "Hello World"
sssss
echo "Hello Linux"
[root@localhost ~]# shell/error.sh
Hello World
shell/error.sh:行4: sssss: 未找到命令
[root@ansible-salve1 shell]# vim info.sh
#!/bin/bash
read -p "Enter some information > " name url age
echo "网站名字:$name"
echo "网址:$url"
echo "年龄:$age"
[root@ansible-salve1 shell]# chmod +x info.sh
[root@ansible-salve1 shell]# ./info.sh
Enter some information > hehao www.baidu.com 18
网站名字:hehao
网址:www.baidu.com
年龄:18
[root@ansible-salve1 shell]#
# 注意:必须在一行内输入所有的值,不能换行,否则只能给第一个变量赋值,后续变量都会赋值失败
十四、只读取一个字符
bash复制代码
# -n 1表示只读取一个字符,运行脚本后,只要用户输入一个字符,立即就读取结束,不等待用户按下回车键
[root@ansible-salve1 shell]# vim info1.sh
#!/bin/bash
read -n 1 -p "Enter a char > " char && printf "\n"
echo "---------------------------------------------------------"
echo $char
[root@ansible-salve1 shell]# chmod +x info1.sh
[root@ansible-salve1 shell]# ./info1.sh
Enter a char > a
---------------------------------------------------------
a
十五、在指定时间内输入密码
bash复制代码
#使用&&组合了多个命令,这些命令会依次执行,并且从整体上作为 if 语句的判断条件,只要其中一个命令执行失败(退出状态为非 0 值),整个判断条件就失败了,后续的命令也就没有必要执行
[root@ansible-salve1 shell]# vim info2.sh
#!/bin/bash
if
read -t 20 -sp "Enter password in 20 seconds(once) > " pass1 && printf "\n" && #第一次输入密码
read -t 20 -sp "Enter password in 20 seconds(again)> " pass2 && printf "\n" && #第二次输入密码
[ $pass1 == $pass2 ] #判断两次输入的密码是否相等
then
echo "Valid password"
else
echo "Invalid password"
fi
[root@ansible-salve1 shell]# chmod +x info2.sh
[root@ansible-salve1 shell]# ./info2.sh
Enter password in 20 seconds(once) >
Enter password in 20 seconds(again)>
Valid password
[root@ansible-salve1 shell]#
十六、利用正则表达式
bash复制代码
[root@ansible-salve1 shell]# vim info3.sh
[root@ansible-salve1 shell]# cat info3.sh
#!/bin/bash
read -p "Are you rich? yes or no: " ANSWER
[[ $ANSWER =~ ^[Yy]|[Yy][Ee][Ss]$ ]] && echo "You Are Rich" || echo "Good Good Study,Day Day up"
[root@ansible-salve1 shell]# chmod +x info3.sh
[root@ansible-salve1 shell]# ./info3.sh
Are you rich? yes or no: y
You Are Rich
[root@ansible-salve1 shell]# ./info3.sh
Are you rich? yes or no: YeS
You Are Rich
[root@ansible-salve1 shell]#