Shell IF,linux if,linux四则运算

【1】四则运算

#!/bin/bash
#你值得收藏的四则表达式运算。  
val1=1
val2=1
val3=1
val4=1
val5=1
val6=1
val7=1

let val1++
((val2++))
val3=$(($val3+1))
val4=`expr $val4 + 1 `
val5=`bc<<<$val5+1`
val6=`echo "$val6+1"|bc`
val7=$[ $val7+1 ]

echo 'val1=' $val1
echo 'val2=' $val2
echo 'val3=' $val3
echo 'val4=' $val4
echo 'val5=' $val5
echo 'val6=' $val6
echo 'val7=' $val7

【2】比较运算

【2.1】数字比较

等于 -eq(equal)

大于 -gt (greater than) 

小于 -lt (less than) 

大于或等于 -ge (greater than or equal) 

小于或等于 -le (less than or equal) 

不相等 -ne (not equal)

int1 -eq int2    两数相等为真 
int1 -ne int2    两数不等为真 
int1 -gt int2    int1大于int2为真 
int1 -ge int2    int1大于等于int2为真 
int1 -lt int2    int1小于int2为真 
int1 -le int2    int1小于等于int2为真

【2.2】字符串比较

str1 == str2      当两个串有相同内容、长度时为真 
str1 != str2      当串str1和str2不等时为真 
-n str1        当串的长度大于0时为真(串非空) 
-z str1        当串的长度为0时为真(空串) 
str1           当串str1为非空时为真

【2.3】文件判断、目录判断

-r file     用户可读为真 
-w file     用户可写为真 
-x file     用户可执行为真 
-f file     文件为正规文件为真 
-d file     文件为目录为真 
-c file     文件为字符特殊文件为真 
-b file     文件为块特殊文件为真 
-s file     文件大小非0时为真 
-t file     当文件描述符(默认为1)指定的设备为终端时为真

【2.4】逻辑运算,与或非

-a         与 
-o        或 
!        非

上面的三种写在括号内;

对应的 && || 写在中括号之间。

例如:

if  [   "$a"  eq   1  -o  "$b" eq 2 ]  &&  [   "$c"  eq  3 ]

【3】特殊行为

【3.1】[]与[[]] 的区别

#[]//不支持正则表达式,竟然是系统命令。
#[[]]//支持正则表达式,却不是系统命令。

 注意:==的功能在[[]]和[]中的行为是不同的,如下:

[[ $a == z* ]] # 如果$a以"z"开头(模式匹配)那么将为true

[[ $a == "z*" ]] # 如果$a等于z*(字符匹配),那么结果为true

在[]中,=和== 做字符串比较,是一样的效果;

【3.2】if判断式子

if判断式
if [ 条件判断一 ] && (||) [ 条件判断二 ]; then
elif [ 条件判断三 ] && (||) [ 条件判断四 ]; then
else
   执行第三段內容程式
fi

【最佳实践】

(1)基本案例

 

#!/bin/bash
#
val=1
if test $val -eq 1;then
echo "hello word!"
fi


#!/bin/bash
#
val=1
if [ $val -eq 1 ];then
echo "hello word!"
fi

#!/bin/bash
#
val=1
[ $val -eq 1 ] && {
echo "hello word!"
}



#!/bin/bash
val=1
[[ $val -eq 1 ]] && {
echo "hello word!"
}
 

#!/bin/bash
#输入一个用户判断该用户是否存在。
#read -p "please input your user:" USER
#a=`cut -d ":" -f1 /etc/passwd| grep "$USER"`

while true
do 
  if [ "$USER" == "$a" ];then
       echo "yes!this user is exit!!!"
       break
    else
       echo "this user no exit!!!"
       read -p "please input it again:" USER
        a=`cut -d ":" -f1 /etc/passwd| grep "$USER"`
   fi
done

 

(2)简单shell 案例,求3个数中的最大值

 read a;read b; read c;
 max=$a
 if [ $max -lt $b ];then max=$b;fi
 if [ $max -lt $c ];then max=$c;fi 
 echo $max
 echo "max:${max},a:${a},b:${b},c:${c}"

  

  

 

注意:分号只是为了体现换号操作,像我们上面写的IF,就没有分号,因为有换行。

 

【参考文档】

https://blog.csdn.net/qq_37960324/article/details/83145412

 

posted @ 2018-01-03 17:28  郭大侠1  阅读(925)  评论(0编辑  收藏  举报