Get the App
SLTechnology News&Howtos  ›  Servers  › 

Conditional statements for shell programming

Shulou Source: shulou.com Published: 2022-06-02 02:18:02 09月19日 Update

shell conditional statement

I. Conditional testing

Test command:

Tests whether a specific expression holds true. When the condition holds, the return value of the test statement is 0, otherwise it is another value.

Format 1: test conditional expression

Format 2:[Conditional Expression] There should be at least one space between the conditional expression and the square brackets.

II. Document testing

[operator file or directory]

Common test operators

-d: Test whether it is Directory

-e: Test whether the directory or file exists (Existing)

-f: Test whether it is a file

-r: Tests whether the current user has permission to read (Read)

-w: Tests whether the current user has permission to write (Write)

-x: Test whether the current user has permission to execute (eXcute)

III. Comparison of integer values

[integer 1 operator integer 2 ]

Common test operators

-eq =(Equal)

-ne: not equal

-gt: Greater Than

It is (less Than)

-le: Less or equal

-ge: Greater or Equal

IV. String Comparison

[String 1 = String 2 ]

[String 1 != String 2 ]

format 2

[ -z string]

Common test operators

=: String content identical

!=:String content is different,! The sign means the opposite.

-z: string content is empty

logic test

Format 1:[Expression 1 ] operator [Expression 2 ]

Format 2: Command 1 Operator Command 2

Common test operators

-a or &&: logical and, meaning "and"

-o or|| logical OR logical OR

!:logical no

Unary operator: i=1

i++: i=$i+1 (i=++i first operation then assignment;i=i++ first assignment in operation)

binary operator

a+b=c

ternary operator

Conditions && Results 1|| results 2

Structure of the if statement

1. single branch structure

2. double branch structure

3. multibranched structure

Tags: Test character string operator condition expression format operation common file structure logic statement content branch command meaning permission user directory Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker Shulou Tech Info Linux vpn OPPO Reno