shell中变量的数值计算常见的命令
(())、let、expr、bc、$[]
一、(())
示例:
[[email protected] ~]# echo $((1+2)) 3
二、let
示例:
[[email protected] ~]# let a=1+2 [[email protected] ~]# echo $a 3
三、expr
示例:
1、
[[email protected] ~]# expr 1+2 1+2
[[email protected] ~]# expr 1 + 2 3
2、
[[email protected] ~]# expr 2 \* 2 4
3、
[[email protected] ~]# expr $[2+3] 5
特殊用法:
判断文件扩展名示例:
[[email protected] ~]# 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
判断输入的是整数还是非整数示例:
[[email protected] 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 [[email protected] 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 :
判断字符的长度示例:
[[email protected] script]# chars=`seq -s " " 100` [[email protected] script]# echo ${#chars} 291 [[email protected] script]# echo $(expr length "$chars") 291
四、bc
## 普通计算 [[email protected] 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. ## 在命令行操作 [[email protected] script]# echo 1+1|bc 2 #进制转换 [[email protected] script]# echo "obase=2;82"|bc 1010010
特殊示例:
[[email protected] script]# echo `seq -s ‘+‘ 10`=`seq -s "+" 10 |bc` 1+2+3+4+5+6+7+8+9+10=55
时间: 2024-10-12 04:17:18