Bash Expression คือ Combination ของ Operators, Features หรือ Values ที่ใช้สร้าง Bash Conditional Statement Conditional Expression อาจเป็น Binary หรือ Unary Expression ที่เกี่ยวกับ Numeric, String หรือ Commands ใดๆ ที่ Return Status เป็นศูนย์เมื่อสำเร็จ
มี Conditional Expressions หลายแบบสำหรับ Test กับ Files นี่คือบางส่วนที่ช่วยได้:
[ -e filepath ] คืนค่า True ถ้า File Exists[ -x filepath ] คืนค่า True ถ้า File Exists และ Executable[ -S filepath ] คืนค่า True ถ้า File Exists และเป็น Socket File[ expr1 -a expr2 ] คืนค่า True ถ้า Expression ทั้งสองเป็น True[ expr1 -o expr2 ] คืนค่า True ถ้า Expression 1 หรือ 2 เป็น True
สำหรับ Conditional Expressions เพิ่มเติมตรวจสอบ Files, Strings และ Numerics โปรดดู Bash Man Page
Bash Example 1. ตรวจสอบ File Existence
Bash Shell Script Code-snippet ต่อไปนี้รับ Filename พร้อม Absolute Path และเช็คว่า File Exists หรือไม่ และโยนข้อมูลที่เหมาะสม
$ cat exist.sh #! /bin/bash file=$1 if [ -e $file ] then echo -e "File $file exists" else echo -e "File $file doesnt exists" fi $ ./exist.sh /usr/bin/boot.ini File /usr/bin/boot.ini exists
อ่านบทความก่อนหน้าเข้าใจ Bash If Statement Types ต่างๆ
Bash Example 2. เปรียบเทียบตัวเลข
Script ด้านล่างอ่าน 2 Integer Numbers จาก User และเช็คว่าทั้ง 2 เท่ากัน มากกว่า หรือน้อยกว่ากัน
$ cat numbers.sh #!/bin/bash echo "Please enter first number" read first echo "Please enter second number" read second if [ $first -eq 0 ] && [ $second -eq 0 ] then echo "Num1 and Num2 are zero" elif [ $first -eq $second ] then echo "Both Values are equal" elif [ $first -gt $second ] then echo "$first is greater than $second" else echo "$first is lesser than $second" fi $ ./numbers.sh Please enter first number 1 Please enter second number 1 Both Values are equal $ ./numbers.sh Please enter first number 3 Please enter second number 12 3 is lesser than 12
ถ้าใหม่กับ Bash Scripting อ่าน Bash Introduction Tutorial
Bash Example 3. Basic Arithmetic Calculator
ตัวอย่างนี้อ่าน Input ซึ่งเป็น Type ของ Arithmetic Operation ที่ต้องการทำกับ Bash Variables (inp1 และ inp2) Arithmetic Operation อาจเป็น Addition, Subtraction หรือ Multiplication
$ cat calculator.sh
#!/bin/bash
inp1=12
inp2=11
echo "1. Addition"
echo "2. Subtraction"
echo "3. Multiplication"
echo -n "Please choose a word [1,2 or 3]? "
read oper
if [ $oper -eq 1 ]
then
echo "Addition Result " $(($inp1 + $inp2))
else
if [ $oper -eq 2 ]
then
echo "Subtraction Result " $(($inp1 - $inp2))
else
if [ $oper -eq 3 ]
then
echo "Multiplication Result " $(($inp1 * $inp2))
else
echo "Invalid input"
fi
fi
fi
$ ./calculator.sh
1. Addition
2. Subtraction
3. Multiplication
Please choose a word [1,2 or 3]?
4
Invalid input
การรู้จัก Bash Special Parameters ($*, $@, $#, $$, $!, $?, $-, $_) จะทำให้ Scripting Life ง่ายขึ้น
Bash Example 4. อ่านและ Ping IP Address
Script ต่อไปนี้ใช้ Read IP Address และเช็คว่า IP Address Reachable หรือไม่ และพิมพ์ข้อความที่เหมาะสม
$ cat ipaddr.sh
#!/bin/bash
echo "Enter the Ipaddress"
read ip
if [ ! -z $ip ]
then
ping -c 1 $ip
if [ $? -eq 0 ] ; then
echo "Machine is giving ping response"
else
echo "Machine is not pinging"
fi
else
echo "IP Address is empty"
fi
$ ./ipaddr.sh
Enter the Ipaddress
10.176.191.106
Pinging 10.176.191.106 with 32 bytes of data:
Reply from 10.176.191.106: bytes=32 time<1ms TTL=128
Ping statistics for 10.176.191.106:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms
Machine is giving ping response
ในตัวอย่างนี้ -z คืนค่า True ถ้า IP Address Zero Length เมื่อ Condition ถูก Preceded โดย ! (Negate) Operator ถ้า Expression เป็น False จะเข้าส่วน If และ Execute ดังนั้นเมื่อ IP Address ไม่ใช่ Null จะเข้าไปเช็คว่า IP Reachable หรือไม่
Bash Example 5. Installer Script
Installer Script ของ Packages หลายๆ ตัวไม่อนุญาต Execute เป็น Root User Script เช็ค User ที่ Execute และโยน Error
Script ต่อไปนี้ อนุญาต Execute Oracle Installer Script ก็ต่อเมื่อ User ที่ Execute เป็น Non-root
$ cat preinstaller.sh #!/bin/bash if [ `whoami` != 'root' ]; then echo "Executing the installer script" ./home/oracle/databases/runInstaller.sh else echo "Root is not allowed to execute the installer script" fi Executing the script as a root user, # ./preinstaller.sh Root is not allowed to execute the installer script
ในตัวอย่างนี้ Output ของ Command whoami เปรียบเทียบกับคำว่า "root" สำหรับ String Comparison ใช้ ==, !=, < และสำหรับ Numeric Comparison ใช้ eq, ne, lt และ gt
Bash Example 6. Enhanced Brackets (Brackets ที่ปรับปรุงแล้ว)
ในตัวอย่างทั้งหมดข้างต้น ใช้ Single Brackets ปิด Conditional Expression แต่ Bash อนุญาต Double Brackets ซึ่งเป็น Enhanced Version ของ Single-Bracket Syntax
$ cat enhanced.sh #!/bin/bash echo "Enter the string" read str if [[ $str == *condition* ]] then echo "String "$str has the word \"condition\"" fi $ ./enhanced.sh Enter the string conditionalstatement String conditionalstatement has the word "condition"
[เป็น Synonym สำหรับ Test Command แม้ Built-in ใน Shell แต่สร้าง Process ใหม่[[เป็น Improved Version ใหม่ ซึ่งเป็น Keyword ไม่ใช่ Program[[เข้าใจโดย Korn และ Bash- ในตัวอย่างข้างต้น ถ้า Variable
$strมี Phrase"condition"อยู่ที่ไหนก็ตาม Condition จะเป็น True - นี่คือ Shell Globbing Feature ซึ่ง Support เฉพาะตอนใช้
[[(Double Brackets) และหลาย Arguments ไม่ต้อง Quoted