Shell และสคริปต์

If / else statements on bash script

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 ComparisonDescription
Str1 == Str2Returns true if the strings are equal
Str1 != Str2Returns true if the strings are not equal
-n Str1Returns true if the string is not null
-z Str1Returns true if the string is null

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

Numeric ComparisonDescription
expr1 -eq expr2Returns true if the expressions are equal
expr1-ne expr2Returns true if the expressions are not equal
expr1 -gt expr2Returns true if expr1 is greater than expr2
expr1 -ge expr2Returns true if expr1 is greater than or equal to expr2
expr1 -lt expr2Returns true if expr1 is less than expr2
expr1 -le expr2Returns true if expr1 is less than or equal to expr2
expr1 -a expr2True if both expr1 and expr2 are true.
expr1 -o expr2True if either expr1 or expr2 is true.
! expr1Negates the result of the expression

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

File ConditionalsDescription
-d dirTrue if the file is a directory
-e file -a fileTrue if the file exists (note that this is not particularly portable, thus -f is generally used)
-f fileTrue if the provided string is a file
-g fileTrue if the group id is set on a file
-k fileTrue if file exists and “sticky” bit is set
-r fileTrue if the file is readable
-s fileTrue if the file has a non-zero size (size greater than zero)
-b fileTrue if file exists and is a block special file
-c fileTrue if file exists and is a character special file
-p fileTrue 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 fileTrue if the user id is set on a file
-w fileTrue if the file is writable
-x fileTrue if the file is an executable
-O fileTrue if file exists and is owned by the effective user id
-G fileTrue if file exists and is owned by the effective group id
-L fileTrue if file exists and is a symbolic link
-S fileTrue if file exists and is a socket.
-N fileTrue if file exists and has been modified since it was last read.
FILE1 -nt FILE2True if FILE1 has been changed more recently than FILE2, or if FILE1 exists and FILE2 does not.
FILE1 -ot FILE2True if FILE1 is older than FILE2, or if FILE2 exists and FILE1 does not.
FILE1 -ef FILE2True if FILE1 and FILE2 refer to the same device and inode numbers.
EOF.← กลับไปอ่านบทความอื่น