Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม Bash

Practical Bash Arithmetic: คู่มือขั้นตอนละเอียดพร้อมตัวอย่าง

คณิตศาสตร์ง่าย Bash scripting ง่าย ดังนั้น arithmetic ใน Bash/Shell scripts ควรจะง่ายเช่นกัน มันจริงๆ แล้วง่าย นี่คือวิธีทำ

การทำงานกับ Integers (จำนวนเต็ม)

Built-in arithmetic ของ Bash จัดการได้เฉพาะ integer (whole number) values หากพยายาม declare variable ด้วยค่า non-integer:

declare -i e=2.5

คุณจะเห็น:

bash: declare: 2.5: syntax error: invalid arithmetic operator (error token is ".5")

เพื่อทำงานกับเลขทศนิยม คุณต้องใช้ external program คำนวณ – แต่ก่อน ลองดูวิธีใช้ built-in Bash arithmetic กับ integers

ใช้ Variable Declaration

หากตัวแปรของคุณ declared เป็น integers ด้วยคำสั่ง declare คุณสามารถ arithmetic ได้โดยไม่ต้องพิจารณาอะไรเพิ่ม:

# Declaring variables as integers declare -i x=4 declare -i y=2 # Performing arithmetic with integer variables result=x/y echo $result

จะคืนค่า:

2

Mathematical statement ไม่ต้อง wrap ใน brackets สำหรับ evaluation หาก variables declared เป็น integers

ใช้ Double Brackets/Parenthesis

หากตัวแปรไม่ได้ declared เป็น integers โดยเฉพาะ ถูกส่งเป็น script parameters หรือ output จากโปรแกรม พวกมันจะถูก treat เป็น strings โดย default

Bash จัดการ strings ใน arithmetic ได้ – แต่ก็ต่อเมื่อ expression ถูก flagged ว่าเป็น arithmetic expression ด้วย double brackets ดูตัวอย่างด้านล่าง:

x = 6 ((y=$x+3)) echo $y

Bash script snippet ข้างต้นจะ output การประเมินค่าที่ถูกต้อง:

9

…เพราะ bracketed arithmetic expression ถูก interpret ให้ถูกต้องว่ามีตัวแปรที่เป็นตัวเลข แทนที่จะ treat เป็น strings

โดยไม่มี brackets:

y=$x+3

คุณจะได้ output:

6+3

นิพจน์จะถูก treat เป็นการ join สอง strings และไม่ถูก evaluate

Mathematical Operators ที่รองรับ

Bash built-in arithmetic รองรับ operators ต่อไปนี้:

+Addition
–Subtraction
++Increment
—Decrement
*Multiplication
/Division
%Remainder (modulo)
**Exponentiation (ยกกำลัง)

Boolean และ Arithmetic

Double brackets ยังปรากฏเมื่อใช้ boolean operators เนื่องจาก evaluated expression จะคืนค่า 0 หรือ 1:

if (( x > y )); then echo "x is greater than y" fi

ดูเพิ่มเติมเกี่ยวกับ Bash Boolean Operations ที่นี่

การทำงานกับ Decimal Values (ทศนิยม)

ใช้คำสั่ง bc

như แสดงไว้ก่อนหน้านี้ การใช้ Bash arithmetic กับ non-integer values จะทำให้ error

คำสั่ง bc จัดการ decimal values ได้ (และคณิตศาสตร์ซับซ้อนมากขึ้น) ไวยากรณ์มีดังนี้:

bc OPTIONS FILE

โดยที่:

  • OPTIONS คือรายการตัวเลือก (ดูรายการเต็มที่นี่)
  • FILE คือ path ไปยังไฟล์ข้อความที่มี arithmetic ที่จะแก้

เนื่องจาก bc รับ input ที่ pipe เข้าได้ คุณไม่ต้องเก็บ equation ในไฟล์ สามารถ pipe เข้าได้โดยตรงจาก console:

echo "2.32+3.45" | bc

…ซึ่งจะ output คำตอบที่ถูกต้อง:

5.77

นี่คือ rundown เต็มๆ เกี่ยวกับ piping และ redirecting command-line applications input และ output

คุณสามารถดู bc user manual เต็มได้โดยรัน:

man bc

มี advanced syntax เยอะมากสำหรับ complex math ของคำสั่ง bc ซึ่งระบุไว้ใน user manual อย่างละเอียด