文件及目录的判断
-F 当它是一个文件且存在时,这个就成立。
[[email protected] shell]# if [ -f 1.txt ]; then echo ok; fi [[email protected] shell]# touch 1.txt [[email protected] shell]# if [ -f 1.txt ]; then echo ok; fi ok
-d 判断他是否是一个目录且存在
[[email protected] shell]# if [ -d /root/ ]; then echo ok; fi ok
-r w x 判断一个文件的权限
[[email protected] shell]# if [ -r /root/ ]; then echo ok; fi 是否可读 ok [[email protected] shell]# if [ -w /root/ ]; then echo ok; fi 是否可写 ok [[email protected] shell]# if [ -x /root/ ]; then echo ok; fi 是否可执行 ok
-n 表示用来判断这个变量是否不为空
[[email protected] shell]# vim if2.sh #!/bin/bash read -p "olease input a number: " n m=`echo $n|sed ‘s/[0-9]//g‘` if [ -n "$m" ] then echo "the character you input is not a number ,please retry. " else echo $n fi
#!/bin/bash read -p "olease input a number: " n m=`echo $n|sed ‘s/[0-9]//g‘` if [ -n "$m" ] then echo "the character you input is not a number ,please retry. " else echo $n fi [[email protected] shell]# sh if2.sh 运行 olease input a number: dasdasdja 输入字母 the character you input is not a number ,please retry. 这不是数字 重新输入 [[email protected] shell]# sh if2.sh olease input a number: 323 输入数字 直接打印 323
查看执行过程
[[email protected] shell]# sh -x if2.sh + read -p ‘olease input a number: ‘ n olease input a number: a ++ sed ‘s/[0-9]//g‘ ++ echo a + m=a + ‘[‘ -n a ‘]‘ + echo ‘the character you input is not a number ,please retry. ‘ the character you input is not a number ,please retry. [[email protected] shell]# sh -x if2.sh + read -p ‘olease input a number: ‘ n olease input a number: 2 ++ sed ‘s/[0-9]//g‘ ++ echo 2 + m= + ‘[‘ -n ‘‘ ‘]‘ + echo 2 2
-z 表示这个变量是否为空
[[email protected] shell]# vim if2.sh #!/bin/bash read -p "olease input a number: " n m=`echo $n|sed ‘s/[0-9]//g‘` if [ -z "$m" ] then echo "the character you input is not a number ,please retry. " else echo $n fi
[[email protected] shell]# sh if2.sh olease input a number: 21323 the character you input is not a number ,please retry. [[email protected] shell]# sh if2.sh olease input a number: dsadasdw dsadasdw
查看执行过程
[[email protected] shell]# sh -x if2.sh + read -p ‘olease input a number: ‘ n olease input a number: 1 ++ sed ‘s/[0-9]//g‘ ++ echo 1 + m= + ‘[‘ -z ‘‘ ‘]‘ + echo ‘the character you input is not a number ,please retry. ‘ the character you input is not a number ,please retry. [[email protected] shell]# sh -x if2.sh + read -p ‘olease input a number: ‘ n olease input a number: dsa ++ sed ‘s/[0-9]//g‘ ++ echo dsa + m=dsa + ‘[‘ -z dsa ‘]‘ + echo dsa dsa
判断一个用户是否存在
[[email protected] shell]# if grep -q ‘^root:‘ /etc/passwd; then echo "root exist." ; fi root exist. [[email protected] shell]# if grep -q ‘^roota:‘ /etc/passwd; then echo "root exist." ; fi
时间: 2024-10-25 04:00:50