Serba Serbi Bash if, elif, else statement
Bash else-if dapat terdiri dari beberapa multiple block statement. Jadi nantinya akan berbentuk seperti anak tangga.
Syntax dari Bash if - elif - else
if <expression>; then <commands> elif <expression>; then <commands> else <commands> fi
<expression> | dapat terdiri dari 1 atau beberapa kondisi boolean |
---|---|
<commands> | Berupa set dari command-command yang akan dijalankan, apabila <condition> bernilai boolean true |
elif | Else if |
Pada anak tangga if-else tersebut, setiap expression akan dikalkulasikan dari atas kebawah.
Contoh:
if-elif Numerik
#!/bin/bash n=2 if [ $n -eq 1 ]; then echo nilai n adalah 1 elif [ $n -eq 2 ]; then echo nilai n adalah 2 else echo nilai n bukan 1 dan 2 fi
~/workspace/bash$ ./bash-elif-example
nilai n adalah 2
#!/bin/bash n=3 if [ $n -eq 1 ]; then echo nilai n adalah 1 elif [[ $n -gt 2 && $n -lt 5 ]]; then echo nilai n lebih besar dari 2 dan lebih kecil dari 5 fi
~/workspace/bash$ ./bash-elif-example
nilai n lebih besar dari 2 dan lebih kecil dari 5
Bash if-elif apabila File exist / ditemukan
if [ ! -f /path/to/file ] then echo "File does not exist in Bash" else echo "File found. Do something meaningful here" fi
Pustaka if-elif
Operator | Returns |
---|---|
-a FILE | True if file exists. |
-b FILE | True if file is block special. |
-c FILE | True if file is character special. |
-d FILE | True if file is a directory. |
-e FILE | True if file exists. |
-f FILE | True if file exists and is a regular file. |
-g FILE | True if file is set-group-id. |
-h FILE | True if file is a symbolic link. |
-L FILE | True if file is a symbolic link. |
-k FILE | True if file has its `sticky' bit set. |
-p FILE | True if file is a named pipe. |
-r FILE | True if file is readable by you. |
-s FILE | True if file exists and is not empty. |
-S FILE | True if file is a socket. |
-t FD | True if FD is opened on a terminal. |
-u FILE | True if the file is set-user-id. |
-w FILE | True if the file is writable by you. |
-x FILE | True if the file is executable by you. |
-O FILE | True if the file is effectively owned by you. |
-G FILE | True if the file is effectively owned by your group. |
-N FILE | True if the file has been modified since it was last read. |
! EXPR | Logical not. |
EXPR1 && EXPR2 | Perform the and operation. |
EXPR1 || EXPR2 | Perform the or operation. |
Dapatkan bonus wallet untuk setiap transaksi di XM hingga $25 per lot. Buka akun trading Wallstreet, nasdaq, snp500 atau forex
Komentar
Posting Komentar