read 在这里介绍两个
read -p 读数
read -t 超时时间
read -p "please input number1:" n1
please input number1:12
另外,判断所输入的参数是不是数字:
if [ $# -ne 2] ; then ##2在这里指的是两个数字
echo "you input is wrong"
exit 1
fi
测试方法test:
格式1:test <>
格式2:[<>]
格式3: [[<>]]
注意: 1和2等价
在[[]]中可以使用通配符进行模式匹配
&&,||,><,等操作符可以用于[[]]中,不能用于[]中(转义可以)
[root@desk ~]# test -f file && echo true||echo false
false ##这两个&&表示,测试结果如果为真则执行前面的(true),如果为假执行后边的(false)
[root@desk ~]# test ! -f file && cat file|| touch fil
##如果不存在file,执行file,存在执行后边的(touch)
中括号的:
[root@desk ~]# [ -f file ]&&echo 1 ||echo 0
0
[root@desk ~]# [ ! -f file ]&&echo 1 ||echo 0
1
[root@desk ~]# [[ ! -f file && -d haha ]]&&echo 1 ||echo 0
0
[root@desk ~]# [ ! -f file && -d haha ]&&echo 1 ||echo 0
-bash: [: missing `]'
0
##在这里表示文件和目录都存在为1,否则为0;下边表示,[]不能加&&
[root@desk ~]# [ ! -f file ] && [ -d haha ]&&echo 1 ||echo 0
0
[root@desk ~]# [ ! -f file -a -d haha ]&&echo 1 ||echo 0
0
##用[]实现[[]]的功能,括号与括号之间用&&;在里面用-a表示*+&&
字符串的测试
test -z ##如果字符串为0,则输出为真
test -n ##如果字符串不为0,则输出为真
test “str1” = “str2” ##成立则为真
test “str1” != “str2” ##不成立则为真
[root@desk ~]# test "asd" == "ad" &&echo 1 || echo 0
0
[root@desk ~]# test "asd" == "asd" &&echo 1 || echo 0
1
[root@desk ~]# test "asd" != "ad" &&echo 1 || echo 0
1
[root@desk ~]# test "asd" != "asd" &&echo 1 || echo 0
0
在[]中使用<,>等符号
[root@desk ~]# [ 2 < 1 ] && echo 1 || echo 0
1 ##可以很明显的看出虽然没有报错,但逻辑存在问题
在单[]中要使用转义符
[root@desk ~]# [ 2 \< 1 ] && echo 1 || echo 0
0 ##这样就ok,还可以使用参数-ge
[root@desk ~]# [ 2 -ge 1 ] && echo 1 || echo 0
1
[root@desk ~]# [ 2 -ge 3 ] && echo 1 || echo 0
0
并且在实际中常常用到:
[root@desk ~]# [ -f /etc/ha ] || ls
1 2 Desktop fil Public test.sh
123 anaconda-ks.cfg Documents Music sysconfig Videos
1.sh a.sh Downloads
##不存在的情况下执行||后边的命令(一般是exit 5 退出)
注意:括号两端必须要有空格!单[]只能用-a,-o,之类
双[[]]可以用&&,||之类
一般而言,还有更简便的方式:
[[ -f "1" ]] && echo 1 ##存在,输出1
[[ -f "1" ]] || echo 0 ##不存在,输出0
如果后边要执行多条命令,需要用大括号括起来
字符串的测试:
file存在
[root@desk ~]# [ -n "$file" ] && echo 1 || echo 0
1 ##-n测试字符串,表示字符串不为0为真
[root@desk ~]# [ -z "$file" ] && echo 1 || echo 0
0 ##-z测试字符串,表示字符串为0为真
字符串比较,必须加引号
[root@desk ~]# test -d /etc && echo 1 ||echo 0
1
[root@desk ~]# test 3 -ne 3 &&echo 1 ||echo 0
0
[root@desk ~]# test "$a" -nt "$b" && echo 1 || echo 0
0 ##-nt比较a和b谁新,-ot比较谁旧(比较的是最后修改时间)
一个简易的菜单选项:
1 #!/bin/bash
2 menu(){
3 cat <<END
4 1.[install lamp]
5 2.[install lnmp]
6 3.[exit]
7 please input the number you want:
8 END
9 }
10 menu
11 read num
12 echo "you already choice: $num"
13 [ "$num" -eq "1" ] &&{
14 echo "starting lamp"
15 #sh /server/lamp.sh
16 }
17
18 [ $num = "2" ] &&{
19 echo "starting lnmp"
20 #/bin/sh /server scripts/lnmp.sh
21 }
22 test "$num" = "3"&& {
23 echo "BYE-BYE"
24 exit
25 }
26 [ $num -ne 1 -a $num -ne 2 -a $num -ne 3 ] && echo "you's input are wrong!"