Note Using expr:
The operator and the number used for the calculation have at least one space around it, otherwise the error
When using multiplication sign, a backslash must be used to mask its specific meaning.
An enterprise-class case study of expr
Because the library is very small, expr is a simple way to determine whether a string is an integer, and the principle is that the variable or string must be an integer rule when expr does the calculation. Add a variable or string to an integer, and if $0 is returned, the variable is an integer.
For example, determine if the output is an integer by passing the parameter:
#!/bin/bashs= ' expr + 4 2>&1 ' a=$?if [$a-eq 0]; Then echo ' This is int ' else echo ' bad ' fi
Judge the input value is not empty;
#!/bin/bashread-p "The first num:" Numread-p "the" the "the" the "the" num2#num=4#num2=if [!] -N $num] && [!-n $num 2]; #-n: Not for zero is true, so use! Take the back then echo "This is a Bab" exit 1fi
Extended:
Programming Ideas
The first level: Determine whether the number of parameters is 2, if not, you are prompted to terminate the run
Second: Determine if the passed in parameter is an integer, if not, then give me a hint to terminate the run
Third off: do the running
#!/bin/bashread-p "The first num:" Numread-p "the" the "the" the "the" num2#num=4#num2=if [!] $num]; #-n: Not for zero is true, so use! Take the reverse or use it! Judging, if it is null, perform the following then echo "This is a Bab" Exit 1fiif [! $num 2]; Then echo "This is a babe" exit 2fiexpr $num + $num 2 + 4 >/dev/null #有点问题if [$?-ne 0]; Then echo ' This must arge ' exit 3fiecho "The IS good" #接下来的计算就很容易了 ~
Special usage of expr: Determine if file extension naming meets requirements
#!/bin/bashif expr "$": ". *\.pub" >/dev/null then echo "Using $" else echo "using bad" fi
Use the expr command to calculate the length:
[Email protected]:/home/xpg# char= "I am oldboy" [Email protected]:/home/xpg# expr Length "$char" 11[email protected]:/ home/xpg# echo ${#char}11[email protected]:/home/xpg# echo $char | Wc-l11
Use a shell script to print words that are not more than 6 in the following statement:
I am Oldboy Linux Welcome to our training
#!/bin/bashchar= "I am oldboy Linux Welcome to We training" for I in $char; Do #echo $i if [' Echo ${#i} '-le 6] >/dev/null # If [' Expr length ' $i '-le 6] >/dev/null can also use expr to calculate length then echo $i Fidone
BC Calculator:
[Email protected]:/home/xpg# echo 8.8-5|bc3.8[email protected]:/home/xpg# echo "scale=2;355/133" |BC #scale = 2 reserved two-bit decimal 2.66[email protected]:/home/xpg#
Use of the expr operator for the shell