|
Bash
Arrays in Bash let you store multiple values in a single variable. Note: Arrays are a Bash feature and are not available in POSIX sh. This example creates an array with four elements. |
|
|
Bash
Access elements using index (0-based). |
|
|
Output:
First fruit: apple Second fruit: banana |
|
|
Bash
Get all elements with |
|
|
Output:
All fruits: apple banana cherry date |
|
|
Bash
Get the number of elements. |
|
|
Output:
Number of fruits: 4 |
|
|
Bash
Add an element to the end. |
|
|
Output:
After adding: apple banana cherry date elderberry |
|
|
Bash
Set a specific index. |
|
|
Output:
After replacing: apple blueberry cherry date |
|
|
Bash
Loop over array elements. |
|
|
Output:
- apple - banana - cherry - date |
|
|
Bash
Get array indices with |
|
|
Output:
Indices: 0 1 2 With indices: [0] = apple [1] = banana [2] = cherry |
|
|
Bash
Array slicing: |
|
|
Output:
First three: apple banana cherry From index 2: cherry date |
|
|
Bash
Check if array is empty. |
|
|
Output:
Array is empty |
|
|
Bash
Create array from command output. |
|
|
Output:
Shell files: ./file3.txt ./file2.txt ./file1.txt |
|
|
Bash
Delete an element (leaves a gap in indices). |
|
|
Output:
After unset [2]: apple banana date Indices now: 0 1 3 |
|
|
Bash
Bash provides associative arrays (hash maps) using |
|
|
Output:
Name: Alice Email: alice@example.com |
|
|
Bash
Iterate over associative array keys: |
|
|
Output:
email: alice@example.com age: 30 name: Alice |
|
|
Bash
Check if a key exists: |
|
|
Bash
Bash provides |
|
|
Output:
root:x:0:0:root:/root:/bin/sh bin:x:1:1:bin:/bin:/sbin/nologin daemon:x:2:2:daemon:/sbin:/sbin/nologin lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin sync:x:5:0:sync:/sbin:/bin/sync shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown halt:x:7:0:halt:/sbin:/sbin/halt mail:x:8:12:mail:/var/mail:/sbin/nologin news:x:9:13:news:/usr/lib/news:/sbin/nologin uucp:x:10:14:uucp:/var/spool/uucppublic:/sbin/nologin cron:x:16:16:cron:/var/spool/cron:/sbin/nologin ftp:x:21:21::/var/lib/ftp:/sbin/nologin sshd:x:22:22:sshd:/dev/null:/sbin/nologin games:x:35:35:games:/usr/games:/sbin/nologin ntp:x:123:123:NTP:/var/empty:/sbin/nologin guest:x:405:100:guest:/dev/null:/sbin/nologin nobody:x:65534:65534:nobody:/:/sbin/nologin |
|
|
Bash
Read only first 5 lines: |
|
|
Output:
root:x:0:0:root:/root:/bin/sh bin:x:1:1:bin:/bin:/sbin/nologin daemon:x:2:2:daemon:/sbin:/sbin/nologin lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin sync:x:5:0:sync:/sbin:/bin/sync |
|
|
Bash
Read from a command using process substitution: |
|
|
Output:
Users: root bin daemon lp sync |
|
|
Bash
Read with a specific delimiter: |
|
|
Output:
Fields: a b c d |
|