What is expr?
expr evaluates the given expression.
4 expr Examples
1. Perform string matching operations
expr command helps us to perform different levels of string matching operations with the operator ‘:’ as shown below,
# partial match and returns the number of characters matched.
$ expr linux : lin
3
# the condition is string 2 entirely should match in string 1.
$ expr linux : linx
0
# regular expression to match any number of characters
$ expr linux : '.*'
5
# to print the matched characters instead of number of matching positions
$ expr linux : '..\(...\)'
nux
Note : expr command should have the space between the operator and operands.
2. Compare the two expressions
Using expr command, you can compare two expressions (numbers or strings). It returns either 0 for failure or 1 for success as shown below
$ var1='10'
$ var2='20'
# matching numbers with '='.
$ expr $var1 = $var2
0
# displays 1 when arg1 is less than arg2
$ expr $var1 \< $var2
1
# display 1 when arg1 is not equal to arg2
$ expr $var1 \!= $var2
1
3. Perform the integer arithmetic operations
You can do the integer arithmetic operations like addition, subtraction, multiplication, division and modulus. In the below example, two numbers are multiplied and the result is produced as follows.
$ expr 5 \* 2
10
4. Increment the value inside the script
The example below increments the $count variable value to 1 inside the shell script.
echo $count
count=`expr $count + 1`
Syntax and Options
expr EXPRESSION
expr OPTION
Short Option | Long Option | Option Description |
---|---|---|
–help | to display help page and exit | |
–version | to display version information and exit | |
ARG1 * ARG2 | Interger arithmetic operator for multiplication | |
ARG1 / ARG2 | Interger arithmetic operator for division | |
ARG1 + ARG2 | Interger arithmetic operator for addition | |
ARG1 – ARG2 | Interger arithmetic operator for substraction | |
ARG1 % ARG2 | Interger arithmetic operator for modulus operation | |
ARG1 = ARG2 | Comparision operator to check both expressions are equals | |
ARG1 < ARG2 | Comparision operator to check arg1 is less than arg2 | |
ARG1 <= ARG2 | Comparision operator to check arg1 is lesser than or equal to arg2 | |
ARG1 > ARG2 | Comparision operator to check arg1 is greater than arg2 | |
ARG1 >= ARG2 | Comparision operator to check arg1 is greater than or equal to arg2 | |
ARG1 != ARG2 | Comparision operator to check arg1 is not equal to arg2 | |
ARG1 : ARG2 | String matching operator | |
ARG1 & ARG2 | Conditional operator which returns arg1 when arg1 and arg2 are not 0 or NUL. otherwise 0. | |
ARG1 | ARG2 | Conditional operator which returns arg1 if it not 0 or NUL otherwise arg2 is returned. |
'리눅스' 카테고리의 다른 글
VMware용 리눅스 가상 이미지 받을 수 있는 사이트 (0) | 2012.11.08 |
---|---|
tcp fastopen - linux kernel 3.6 이상 (0) | 2012.11.02 |
ip_dynaddr - 유동 ip인지, 고정 ip인지 확인하기 (0) | 2012.10.04 |
evernote + ubuntu = everpad (0) | 2012.09.21 |
swap 파일 추가로 리눅스 스왑공간 늘리기 (0) | 2012.05.04 |