字符测试

bash编程之:字符测试

双目:
    >:大于
    <:小于
    ==:等于,等值比较
    =~:左侧是字符串,右侧是一个模式,判定右侧的字符串能否被左侧的模式匹配:通常只在[[]]中使用
    模式中可以使用行首,行尾锚定符;但模式不要加引号
    所有符号前后都要有空格
单目:
    -n $stringVar:字符串是否不空,不空为真,空为假
    -z $stringVar:字符串是否为空,空为真,不空为假
[root@localhost kayshi]# stringA="root"
[root@localhost kayshi]# stringB="hello"
[root@localhost kayshi]# [ "$stringA" == "$stringB" ]
[root@localhost kayshi]# echo $?
1
[root@localhost kayshi]# stringB="root"
[root@localhost kayshi]# [ "$stringA" == "$stringB" ]
[root@localhost kayshi]# echo $?
0
=注意:最好给字符串加引号:这是因为如果stringA或stringB没有值,不加引号会报错,认为这不是字符串,加上引号,就是空字符
[root@localhost kayshi]# [ -n "$stringA" ]
[root@localhost kayshi]# echo $?
0
[root@localhost kayshi]# [ -z "$stringA" ]
[root@localhost kayshi]# echo $?
1
[root@localhost kayshi]# [[ "$stringA"=~ot ]]
[root@localhost kayshi]# echo $?
0
测试用户的shell,是不是以sh结尾的:
[kayshi@localhost ~]$ [[ `grep "^root\>" /etc/passwd | cut -d: -f7` =~ sh$ ]]
[kayshi@localhost ~]$ echo $?
0
[kayshi@localhost ~]$ [[ `grep "^bin\>" /etc/passwd | cut -d: -f7` =~ sh$ ]]
[kayshi@localhost ~]$ echo $?
1
注意 =~ 左右各要一个空格,否则结果总为真

判断所有用户是否是可登陆用户:
#!/bin/bash
for userName in `cut -d: -f1 /etc/passwd`; do
        if [[ `grep "^$userName\>" /etc/passwd | cut -d: -f7` =~ sh$ ]]; then
                echo "login user: $userName"
        else
                echo "nologin user: $userName"
        fi
done

练习:写一个脚本
1.让用户交互式输入一个用户名,先判定用户是否存在,不存在,则以7为退出码
2.判断用户的shell是否为/bin/bash;如果是,则显示“Bash User”,退出码为0,否则显示为“Not Bash User”,退出码为1
练习:
1.显示菜单如下

     cpu) show CPU info
     mem) show memory info
     quit) quit
     Enter you option

2.如果用户选择cpu,显示文件/proc/cpuinfo的信息
3.如果用户选择mem,显示文件/proc/memnfo的信息
4.如果用户选择quit,则退出,退出码为5
5.如果用户选择其他字符,显示位置选项,请重新执行脚本,退出码为6

#!/bin/bash
cat << EOF
========================
cpu) show CPU info
mem) show memory info
quit) quit
Enter you option:
========================
EOF
read -p "input: " select
if [ "$select" == "cpu" ];then
        cat /proc/cpuinfo
elif [ "$select" == "mem" ];then
        cat /proc/meminfo
elif [ "$select" == "quit" ];then
        exit 5
else
        echo "invaild option,please reexecute the script "
        exit 6
fi
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值