Files
linux.softwareshinobi.com/landing/docs/Bash-Scripts/008-bash-arrays.md

98 lines
1.6 KiB
Markdown
Raw Permalink Normal View History

2025-06-19 10:03:08 -04:00
# Arrays
Arrays are essential. They let a single variable hold multiple values. Initialize them by listing values, separated by spaces, inside parentheses:
```bash
# Example initialization:
my_array=("value 1" "value 2" "value 3" "value 4")
```
Access array elements using their numeric index. **Always use curly brackets.**
Let's create `arrays.sh` to demonstrate:
```bash
touch arrays.sh
```
Now, open `arrays.sh` and add:
```bash
#!/usr/bin/env bash
my_array=("value 1" "value 2" "value 3" "value 4")
echo "Second element (index 1): ${my_array[1]}"
echo "Last element (index -1): ${my_array[-1]}"
echo "All elements: ${my_array[@]}"
echo "Total elements: ${#my_array[@]}"
```
Save and exit. Make it executable:
```bash
chmod +x arrays.sh
```
Run your script:
```bash
./arrays.sh
```
Output:
```
value 2
value 4
value 1 value 2 value 3 value 4
4
```
### Slicing
Extract specific portions of an array or string using slicing notation.
Create `slicing.sh`:
```bash
touch slicing.sh
```
Open `slicing.sh` and add these examples:
```bash
#!/usr/bin/env bash
letters=("A" "B" "C" "D" "E")
echo "Original array: ${letters[@]}"
echo "Example 1 (start 0, length 2): ${letters:0:2}" # Prints AB
echo "Example 2 (start 0, all elements): ${letters::5}" # Prints ABCDE
echo "Example 3 (start 3, to end): ${letters:3}" # Prints DE
```
Save and exit. Make it executable:
```bash
chmod +x slicing.sh
```
Run `slicing.sh`:
```bash
./slicing.sh
```
Output:
```
A B C D E
AB
ABCDE
DE
```
Mastering arrays and slicing gives you precise control over your data structures.