read+if+test+for+while

版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/qq_41729148/article/details/89076863

read命令:从键盘中读取变量的值,如果没有指定变量名,数据将会被送入REPLY中。

read参数
s:隐藏信息
t:限制时间
n:限制长度
r:允许输入特殊字符
p:给出提示符

read的简单应用

#s参数会隐藏信息
[root@aaa ~]# read -s passwd 
[root@aaa ~]# echo $passwd
123456
#t参数会限制输入内容的时间
[root@aaa ~]# read -t 2 passwd1
#n会限制输入字符的长度,也就是你只能输入5个字符
[root@aaa ~]# read -n 5 passwd2
qwert[root@aaa ~]# 
#r可以输入特殊的字符
[root@aaa ~]# read -r c
/dev/sdb
[root@aaa ~]# echo $c
/dev/sdb
#用来打印说明信息
[root@aaa ~]# read -p "input a number" a
input a number44
[root@aaa ~]# echo $a
44

if语句

#单分支if
#!/bin/bash
if ls /mnt
then
        echo "it is ok"
fi  
#双分支if
#!/bin/bash
if grep root /etc/passwd;then
        echo "it is ok"
else
        echo "it is error"
fi
#多分支if
#!/bin/bash
read -p "input a username:" name
if grep $name /etc/passwd;then
        echo "the user $name exists on this system"
elif ls -d /home/$name;then
        echo "the user $name not exists on this system"
        echo "the user $name has a home directory"
else
        echo "the user $name not exists on this system"
        echo "the user $name has not  a home directory"
fi

test测试命令,可以用来测试数值,文件,字符3大方面的内容

数值比较

参数 说明
eq 等于为真
ne 不等于为真
gt 大于为真
ge 大于等于为真
lt 小于为真
le 小于等于为真

test数值测试实例

#!/bin/bash
if test 2 -eq 1;then
        echo ok
else
        echo error
fi

if [ 2 -eq 2 ];then
        echo ok
else
        echo error
fi
#!/bin/bash
read -p "input var1 var2:" var1 var2
if [ $var1 -gt $var2 ];then
        echo "$var1 > $var2"
elif [ $var1 -lt $var2 ];then
        echo "$var1 < $var2"
else
        echo "$var1 = $var2"
fi

字符串的比较

== 等于为真
!= 不等于为真
-z 长度为0为真
-n 长度不为空为真
>,< 大于或者小于为真,分开,根据ascII判断

字符串测试实例

#!/bin/bash 
read -p "input your name:" name
if [ $name == "root" ];then
        echo "you are super administartor"
else
        echo " you are a general user"
fi

文件测试

参数 说明
e 目录/文件存在为真
r 文件存在且可读为真
w 文件存在且可写为真
x 文件存在且可执行为真
s 文件存在且至少有一个字符
d 文件存在且为目录为真
f 文件存在且为普通文件为真
r 如果文件存在且为字符型文件则为真
b 如果文件存在且为块特殊文件则为真

test测试文件

#!/bin/bash
if [ -e /etc/passwd ];then
        echo ok
else
        echo error
fi    

通配符

字符 含义
* 0或者任意多个字符
任意一个字符
[list] list中任意一个字符
[c-b] c到b中的任意一个字符
{str1,str2} {}中的任意一个字符串

case语句

#!/bin/bash
cat << eof
*******************
1.backup
2.copy
3.quit
*******************
eof
read -p "input your choice:" op
case $op in
        1|backup)
        echo "backup is running"
        ;;
        2|copy)
        echo "copy is running"
        ;;
        3|quit)
        exit 10
        ;;
        *)
        echo error
esac

for语句

#!/bin/bash
for i in `cat /etc/passwd`
do
        echo $i
done
#!/bin/bash
for((i=1 ; i<=10 ;i++ ))
do
        echo num is $i
done 

99乘法表

#!/bin/bash:w
for i in `seq 9`
do
        for j in `seq $i`
        do
                echo -n " $i*$j=`echo $(($i*$j))` "
        done
        echo " "
done

while语句

#!/bin/bash
var=10
while [ $var -gt 0 ]
do
        echo $var
        var=$[$var-1]
done   

猜你喜欢

转载自blog.csdn.net/qq_41729148/article/details/89076863