Files
linux.softwareshinobi.com/landing/docs/Bash-Scripts/008-bash-arrays.md
Software Shinobi 7d9171c854
All checks were successful
learn org at code.softwareshinobi.com/linux.softwareshinobi.com/pipeline/head This commit looks good
reworking content
2025-06-19 10:03:08 -04:00

1.6 KiB

Arrays

Arrays are essential. They let a single variable hold multiple values. Initialize them by listing values, separated by spaces, inside parentheses:

# 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:

touch arrays.sh

Now, open arrays.sh and add:

#!/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:

chmod +x arrays.sh

Run your script:

./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:

touch slicing.sh

Open slicing.sh and add these examples:

#!/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:

chmod +x slicing.sh

Run slicing.sh:

./slicing.sh

Output:

A B C D E
AB
ABCDE
DE

Mastering arrays and slicing gives you precise control over your data structures.