Numerical calculation of variables in shell common commands
(()), let, expr, BC, $[]
One, (())
Example:
[[Email Protected]hell ~]# echo $ ((1+2)) 3
Second, let
Example:
[[email protected] ~]# let a=1+2 [[email protected] ~]# echo $a 3
Third, expr
Example:
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
Special usage:
To determine the file extension example:
[[email protected] ~]# vim ' which ssh-copy-id ' # Judge file extensions # check if we have 2 parameters left, if so the first is the new id file if [ -n "$" ]; then if xpr "$" : ". *\.pub" > /dev/null ; then id_file= "$" else id_file= "$1.pub" fi shift # and this should leave $1 as the target name fi
determines whether an integer or non-integer input is an example:
[[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 :
Example of determining the length of a character:
[Email protected] script]# chars= ' seq-s "[[email protected] script]# echo ${#chars} 291 [[Email Protect ED] script]# echo $ (expr length "$chars") 291
Four, BC
## General Calculation     [[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. ## On the command line Operations [[email protected] script]# echo 1+1|bc 2 #进制转换 [[email protected] script]# echo "obase=2;82" |bc 1010010
Special Examples:
[[email protected] script]# echo ' seq-s ' + ' + ' = ' seq-s ' + ' |BC ' 1+2+3+4+5+6+7+8+9+10=55
This article is from the "topspeed_king" blog, make sure to keep this source http://mylinuxlife.blog.51cto.com/4706737/1683032
Calculations in the shell