bash
สรุปการใช้ If / else statements บน Bash script พร้อมทั้งเงื่อนไขการเปรียบเทียบ

ใน bash จะมีการใช้งาน If / else statements ดังนี้

  1. การใช้ if เพื่อเปรียบเทียบทั่วไป
    if [ condition ]
    then
    ...
    fi
  2. การใช้ if และ else เพื่อเปรียบเทียบ
    if [ condition ]
    then
    ...
    else
    ...
    fi
  3. การใช้ if, elif (else if) และ else เพื่อเปรียบเทียบ
    if [ condition ]
    then
    ...
    elif [ condition ]
    then
    ...
    else
    ...
    fi

ในการเปรียบเทียบ condition สามารถตรวจสอบได้หลากหลายซึ่งสามารถสรุปรวมได้ดังนี้

Operation สำหรับเปรียบเทียบ string

String Comparison

Description

Str1 == Str2

Returns true if the strings are equal

Str1 != Str2

Returns true if the strings are not equal

-n Str1

Returns true if the string is not null

-z Str1

Returns true if the string is null

Operation สำหรับเปรียบเทียบตัวเลข

Numeric Comparison

Description

expr1 –eq expr2

Returns true if the expressions are equal

expr1-ne expr2

Returns true if the expressions are not equal

expr1 –gt expr2

Returns true if expr1 is greater than expr2

expr1 –ge expr2

Returns true if expr1 is greater than or equal to expr2

expr1 –lt expr2

Returns true if expr1 is less than expr2

expr1 -le expr2

Returns true if expr1 is less than or equal to expr2

expr1 –a expr2

True if both expr1 and expr2 are true.

expr1 -o expr2

True if either expr1 or expr2 is true.

! expr1

Negates the result of the expression

Operation สำหรับตรวจสอบไฟล์

File Conditionals

Description

-d dir

True if the file is a directory

-e file

-a file

True if the file exists (note that this is not particularly portable, thus -f is generally used)

-f file

True if the provided string is a file

-g file

True if the group id is set on a file

-k file

True if file exists and “sticky” bit is set

-r file

True if the file is readable

-s file

True if the file has a non-zero size (size greater than zero)

-b file

True if file exists and is a block special file

-c file

True if file exists and is a character special file

-p file

True if file exists and is a named pipe (FIFO)

-t [fd]

True if file descriptor fd is open and refers to a terminal. If fd is omitted, it defaults to 1 (standard output).

-u file

True if the user id is set on a file

-w file

True if the file is writable

-x file

True if the file is an executable

-O file

True if file exists and is owned by the effective user id

-G file

True if file exists and is owned by the effective group id

-L file

True if file exists and is a symbolic link

-S file

True if file exists and is a socket.

-N file

True if file exists and has been modified since it was last read.

FILE1 -nt FILE2

True if FILE1 has been changed more recently than FILE2, or if FILE1 exists and FILE2 does not.

FILE1 -ot FILE2

True if FILE1 is older than FILE2, or if FILE2 exists and FILE1 does not.

FILE1 -ef FILE2

True if FILE1 and FILE2 refer to the same device and inode numbers.