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

เชี่ยวชาญ Bash Arrays: 15 ตัวอย่างปฏิบัติและบทช่วยสอนครบถ้วน

Array คือ Variable ที่มี Multiple Values อาจเป็น Same Type หรือ Different Type ไม่มี Maximum Limit สำหรับ Size ของ Array และไม่มี Requirement ว่า Member Variables ต้อง Indexed หรือ Assigned Contiguously Array Index เริ่มจากศูนย์

ในบทความนี้ มาทบทวน Array Operations 15 แบบใน Bash

บทความนี้เป็นส่วนหนึ่งของชุด Bash Tutorial Series ต่อเนื่อง สำหรับมือใหม่ Bash Scripting เริ่มต้นจาก Bash Scripting Introduction Tutorial

1. Declaring an Array และ Assigning Values

ใน Bash Array สร้างอัตโนมัติเมื่อ Variable ใช้ใน Format เหมือน:

name[index]=value
  • name คือชื่อ Array ใดๆ
  • index อาจเป็น Number หรือ Expression ใดๆ ที่ Evaluate เป็น Number มากกว่าหรือเท่ากับศูนย์ สามารถ Declare Explicit Array ด้วย declare -a arrayname
$ cat arraymanip.sh
#! /bin/bash
Unix[0]='Debian'
Unix[1]='Red hat'
Unix[2]='Ubuntu'
Unix[3]='Suse'
echo ${Unix[1]}
$./arraymanip.sh
Red hat

เข้าถึง Element จาก Array ใช้ Curly Braces เหมือน ${name[index]}

2. Initializing an Array ระหว่าง Declaration

แทนที่จะ Initialize แต่ละ Element แยกกัน สามารถ Declare และ Initialize Array ได้โดยระบุ List of Elements (คั่นด้วย White Space) ใน Curly Braces

Syntax: declare -a arrayname=(element1 element2 element3)

ถ้า Elements มี White Space Character ให้ Enclose ใน Quotes

#! /bin/bash
$cat arraymanip.sh
declare -a Unix=('Debian' 'Red hat' 'Red hat' 'Suse' 'Fedora');

declare -a Declares Array และ Elements ทั้งหมดใน Parentheses เป็น Elements ของ Array

3. Print the Whole Bash Array (พิมพ์ Array ทั้งหมด)

มีวิธีต่างๆ พิมพ์ Whole Elements ของ Array ถ้า Index Number เป็น @ หรือ * All Members ของ Array จะ Referenced สามารถ Traverse ผ่าน Array Elements และ Print ด้วย Looping Statements ใน Bash

echo ${Unix[@]}  # Add the above echo statement into the arraymanip.sh
#./t.sh
Debian Red hat Ubuntu Suse

Refer เนื้อหา Member Variable ของ Array โดยไม่ให้ Index Number เท่ากับ Refer เนื้อหา Element แรก Index Number ศูนย์

4. Length of the Bash Array (ความยาวของ Array)

ได้ Length ของ Array ด้วย Special Parameter $#

${#arrayname[@]} ให้ Length ของ Array

$ cat arraymanip.sh
declare -a Unix=('Debian' 'Red hat' 'Suse' 'Fedora');
echo ${#Unix[@]}  # Number of elements in the array
echo ${#Unix}     # Number of characters in the first element of the array.i.e Debian
$./arraymanip.sh
4
6

5. Length of the nth Element ใน Array

${#arrayname[n]} ควรให้ Length ของ Nth Element ใน Array

$cat arraymanip.sh
#! /bin/bash
Unix[0]='Debian'
Unix[1]='Red hat'
Unix[2]='Ubuntu'
Unix[3]='Suse'
echo ${#Unix[3]}  # Length of element at index 3 i.e Suse
$./arraymanip.sh
4

6. Extraction by Offset และ Length สำหรับ Array

ตัวอย่างต่อไปนี้แสดงวิธี Extract 2 Elements เริ่มจาก Position 3 จาก Array ชื่อ Unix

$cat arraymanip.sh
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
echo ${Unix[@]:3:2}
$./arraymanip.sh
Suse Fedora

ตัวอย่างข้างต้นคืนค่า Elements ใน Index 3 และ 4 Index เริ่มจากศูนย์เสมอ

7. Extraction ด้วย Offset และ Length สำหรับ Element เฉพาะของ Array

Extract แค่ 4 Characters แรกจาก Array Element เช่น Ubuntu ที่อยู่ Index 2 ของ Array ใช้ Offset และ Length สำหรับ Element เฉพาะ

$cat arraymanip.sh
#! /bin/bash
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
echo ${Unix[2]:0:4}
./arraymanip.sh
Ubun

ตัวอย่างข้างต้น Extract 4 Characters แรกจาก Element Index 2 ของ Array

8. Search และ Replace ใน Array Elements

ตัวอย่างต่อไปนี้ Search Ubuntu ใน Array Elements และ Replace ด้วยคำว่า 'SCO Unix'

$cat arraymanip.sh
#!/bin/bash
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
echo ${Unix[@]/Ubuntu/SCO Unix}
$./arraymanip.sh
Debian Red hat SCO Unix Suse Fedora UTS OpenLinux

ในตัวอย่างนี้ Replace Element ใน Index 2 'Ubuntu' ด้วย 'SCO Unix' แต่ Example นี้จะไม่ Replace Array Content อย่างถาวร

9. เพิ่ม Element ให้ Existing Bash Array

ตัวอย่างต่อไปนี้แสดงวิธี Add Element ให้ Existing Array

$cat arraymanip.sh
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
Unix=("${Unix[@]}" "AIX" "HP-UX")
echo ${Unix[7]}
$./arraymanip.sh
AIX

ใน Array ชื่อ Unix Elements 'AIX' และ 'HP-UX' ถูกเพิ่มใน Index 7 และ 8 ตามลำดับ

10. Remove an Element จาก Array

unset ใช้ Remove Element จาก Array unset จะมี Effect เหมือน Assign Null ให้ Element

$cat arraymanip.sh
#!/bin/bash
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
unset Unix[3]
echo ${Unix[3]}

Script ข้างต้นจะพิมพ์ Null ซึ่งค่าใน Index 3 ตัวอย่างต่อไปนี้แสดงหนึ่งในวิธี Remove Element ออกจาก Array อย่างสมบูรณ์

$ cat arraymanip.sh
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
pos=3
Unix=(${Unix[@]:0:$pos} ${Unix[@]:$(($pos + 1))})
echo ${Unix[@]}
$./arraymanip.sh
Debian Red hat Ubuntu Fedora UTS OpenLinux

ในตัวอย่างนี้ ${Unix[@]:0:$pos} ให้ 3 Elements เริ่มจาก Index 0 คือ 0,1,2 และ ${Unix[@]:4} ให้ Elements จาก Index 4 ถึง Last และ Merge ทั้งสอง Output นี้เป็น Workaround หนึ่งในการ Remove Element จาก Array

11. Remove Bash Array Elements ใช้ Patterns

ใน Search Condition ให้ Patterns และ Store Remaining Elements ไป Array อื่น

$ cat arraymanip.sh
#!/bin/bash
declare -a Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora');
declare -a patter=( ${Unix[@]/Red*/} )
echo ${patter[@]}
$ ./arraymanip.sh
Debian Ubuntu Suse Fedora

ตัวอย่างข้างต้น Remove Elements ที่มี Pattern Red*

12. Copying an Array (คัดลอก Array)

Expand Array Elements และ Store ไป New Array

#!/bin/bash
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
Linux=("${Unix[@]}")
echo ${Linux[@]}
$ ./arraymanip.sh
Debian Red hat Ubuntu Fedora UTS OpenLinux

13. Concatenation ของ 2 Bash Arrays

Expand Elements ของ 2 Arrays และ Assign ไป New Array

$cat arraymanip.sh
#!/bin/bash
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
Shell=('bash' 'csh' 'jsh' 'rsh' 'ksh' 'rc' 'tcsh');
UnixShell=("${Unix[@]}" "${Shell[@]}")
echo ${UnixShell[@]}
echo ${#UnixShell[@]}
$ ./arraymanip.sh
Debian Red hat Ubuntu Suse Fedora UTS OpenLinux bash csh jsh rsh ksh rc tcsh
14

Print Array ที่มี Elements ของทั้ง 'Unix' และ 'Shell' จำนวน Elements ของ Array ใหม่คือ 14

14. Deleting an Entire Array (ลบ Array ทั้งหมด)

unset ใช้ Delete Entire Array

$cat arraymanip.sh
#!/bin/bash
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
Shell=('bash' 'csh' 'jsh' 'rsh' 'ksh' 'rc' 'tcsh');
UnixShell=("${Unix[@]}" "${Shell[@]}")
unset UnixShell
echo ${#UnixShell[@]}
$ ./arraymanip.sh
0

หลัง Unset Array Length จะเป็นศูนย์

15. Load Content of a File ลง Array

Load Content ของ File บรรทัดต่อบรรทัดลง Array ได้

#Example file
$ cat logfile
Welcome to thegeekstuff
Linux
Unix
$ cat loadcontent.sh
#!/bin/bash
filecontent=( `cat "logfile" `)
for t in "${filecontent[@]}"
do
  echo $t
done
echo "Read file content!"
$ ./loadcontent.sh
Welcome
to
thegeekstuff
Linux
Unix
Read file content!

ในตัวอย่างข้างต้น แต่ละ Index ของ Array Element พิมพ์ผ่าน For Loop

Recommended Reading

Bash 101 Hacks, by Ramesh Natarajan ผมใช้เวลาส่วนใหญ่กับ Linux Environment จึงเป็นแฟนใหญ่ของ Bash Command Line และ Shell Scripting 15 ปีก่อน ทำงานบน *nix หลายรสชาติ เคยเขียน Code มากบน C Shell และ Korn Shell ต่อมาเริ่มทำงานบน Linux เป็น System Administrator Automate ทุกอย่างที่เป็นไปได้ด้วย Bash Shell Scripting จากประสบการณ์ Bash เขียน Bash 101 Hacks eBook ที่มี 101 ตัวอย่างปฏิบัติทั้ง Command Line และ Shell Scripting หากคิดจะ Master Bash ให้ทำความดีใจตัวเองและอ่านหนังสือเล่มนี้ จะช่วยให้ควบคุม Bash Command Line และ Shell Scripting ได้อย่างเต็มที่