Get the App
SLTechnology News&Howtos  ›  Servers  › 

Linux expr command

Shulou Source: shulou.com Published: 2022-06-02 09:06:34 09月20日 Update

The expr command is generally used for integer values, but it can also be used for strings.

1.expr counter function.

Expr 10 + 10

twenty

Expr 1500 + 900,

2500

Expr 30 / 3

ten

Expr 30 / 3 / 2

five

(note that there are spaces on the left and right of the operator)

When using a multiplication sign, its specific meaning must be masked with a backslash. Because shell may misunderstand the meaning of showing an asterisk.

Expr 30\ * 3

ninety

two。 Calculate the string length

Expr length "this is a test"

fourteen

3. Grab the string

Expr substr "this is a test" 3 5

Is is

4. Grab the position where the first character number string appears

Expr index "sarasara" a

two

5.expr incremental count

Expr is used for incremental calculations in loops. First, the loop is initialized to 0, then the loop value is added by 1, and the usage meaning of the backquotation mark

LOOP=0

LOOP= `expr $LOOP + 1`

6.expr determines whether it is an integer or not

You can test a number with expr. If you try to evaluate a non-integer, an error is returned.

Rr=1.1

Expr $rr + 1

Expr: non-numeric argument

Rr=2

Expr $rr + 1

three

(note: this example is different from the original)

Here you need to assign a value to the variable (regardless of its contents), perform a numerical operation, and import the output into dev/null

Then test the status of the final command, if it is 0, it is proved to be a number, and the others are indicated as non-numeric values.

Value=12

Expr $value + 10 > / dev/null 2 > & 1

Echo $?

0

This is an integer.

Value=hello

Expr $value + 10 > / dev/null 2 > & 1

Echo $?

two

This is a non-numeric character.

7.expr itself has an exit status of 1

Expr can also return its own exit status. Unfortunately, the return value is the opposite of the system's last exit command, successfully returning 1, and any other value is invalid or incorrect. The following example tests whether two strings are equal, where the strings are "hello" and "hello".

Value=hello

Expr $value = "hello"

one

Echo $?

0

Expr returns 1. Don't be confused, it shows success. Now check its final exit status. If you return 0, the test is successful.

"hello" really equals "hello".

8. Pattern matching:

Expr also has pattern matching capabilities. You can use expr to calculate the number of characters in a string by specifying the colon option. . * means that any character is repeated 0 or more times.

Value=accounts.doc

Expr $value:'. *'

twelve

Tags: Character string numeric value state test command success integer this is loop number example function increment pattern error operation different unfortunately two Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Xiaomi macOS Redmi MariaDB