shell中變量的數值計算常見的命令shell
(())、let、expr、bc、$[]vim
1、(())bash
示例:
ssh
[root@shell ~]# echo $((1+2)) 3
2、letide
示例:this
[root@shell ~]# let a=1+2 [root@shell ~]# echo $a 3
3、expr命令行
示例:ip
一、
get
[root@shell ~]# expr 1+2 1+2
[root@shell ~]# expr 1 + 2 3
二、
input
[root@shell ~]# expr 2 \* 2 4
三、
[root@shell ~]# expr $[2+3] 5
特殊用法:
判斷文件擴展名示例:
[root@shell ~]# vim `which ssh-copy-id ` # 判斷文件擴展名 # check if we have 2 parameters left, if so the first is the new ID file if [ -n "$2" ]; then if xpr "$1" : ".*\.pub"> /dev/null ; then ID_FILE="$1" else ID_FILE="$1.pub" fi shift # and this should leave $1 as the target name fi
判斷輸入的是整數仍是非整數示例:
[root@shell script]# cat expr.sh #!/bin/bash while true do read -p "Pls input :" a expr $a + 0 > /dev/null 2>&1 [ $? -eq 0 ] && echo int || echo chars done [root@shell script]# sh expr.sh Pls input :2 int Pls input :3 int Pls input :a chars Pls input :i chars Pls input :> chars Pls input :
判斷字符的長度示例:
[root@shell script]# chars=`seq -s " " 100` [root@shell script]# echo ${#chars} 291 [root@shell script]# echo $(expr length "$chars") 291
4、bc
## 普通計算 [root@shell script]# bc bc 1.06.95 Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc. This is free software with ABSOLUTELY NO WARRANTY. For details type `warranty'. 1+2 3 1.3+2 3.3 2*3 6 ^C (interrupt) Exiting bc. ## 在命令行操做 [root@shell script]# echo 1+1|bc 2 #進制轉換 [root@shell script]# echo "obase=2;82"|bc 1010010
特殊示例:
[root@shell script]# echo `seq -s '+' 10`=`seq -s "+" 10 |bc` 1+2+3+4+5+6+7+8+9+10=55