
Part 1 : Arrays in Bash
An array is a variable that can hold multiple values at once. Unlike many programming languages, Bash only supports one-dimensional arrays, but they’re extremely useful.
1️⃣ Declaring Arrays
You can create an array simply by assigning values in parentheses:
$$
fruits=(“apple” “banana” “cherry”)
$$
You can also assign values individually:
$$
fruits[0]=“apple”
fruits[1]=“banana”
fruits[2]=“cherry”
$$
2️⃣ Accessing Array Elements
Array elements are accessed using their index (starting from 0
):
$$
echo “${fruits[0]}” # apple
echo “${fruits[1]}” # banana
$$
3️⃣ Printing All Elements
$$
echo “${fruits[@]}” # apple banana cherry
echo “${fruits[*]}” # apple banana cherry
$$
4️⃣ Array Length
$$
echo “${#fruits[@]}” # 3
$$
5️⃣ Adding Elements
$$
fruits[3]=“mango”
echo “${fruits[@]}” # apple banana cherry mango
$$
6️⃣ Deleting Elements
$$
unset fruits[1]
echo “${fruits[@]}” # apple cherry mango
$$
7️⃣ Iterating Over Arrays
$$
for fruit in “${fruits[@]}”; do
echo “I like $fruit”
done
$$
8️⃣ Slicing Arrays
You can extract a portion of an array:
$$
numbers=(0 1 2 3 4 5 6 7 8 9)
echo “${numbers[@]:2:4}” # 2 3 4 5
$$
9️⃣ Associative Arrays (Key-Value Pairs)
Bash 4+ supports associative arrays (like dictionaries).
$$
declare -A capital
capital[“Nepal”]=“Kathmandu”
capital[“India”]=“New Delhi”
capital[“Japan”]=“Tokyo”
echo "${capital[“Nepal”]}" # Kathmandu
$$
Looping through keys and values:
$$
for country in “${!capital[@]}”; do
echo “$country -> ${capital[$country]}”
done
$$
Part 2 : String Manipulation in Bash
Strings are everywhere — filenames, user inputs, logs. Bash provides built-in operators for powerful string handling.
1️⃣ String Length
$$
str=“Hello World”
echo “${#str}” # 11
$$
2️⃣ Extracting Substrings
$$
echo “${str:0:5}” # Hello
echo “${str:6}” # World
$$
3️⃣ Replacing Substrings
$$
str=“I love bash”
echo “${str/bash/python}” # I love python
$$
4️⃣ Removing Prefix and Suffix
$$
filename=“report2025.txt”
echo “${filename%.txt}” # report2025 (remove suffix)
echo “${filename#report}” # 2025.txt (remove prefix)
$$
5️⃣ String Comparison
$$
a=“hello”
b=“world”
if [[ “$a” == “$b” ]]; then
echo “Equal”
else
echo “Not equal”
fi
$$
6️⃣ Concatenation
$$
str1=“Hello”
str2=“World”
echo “$str1 $str2” # Hello World
$$
7️⃣ Checking for Substring
$$
text=“Bash scripting is fun”
if [[ “$text” == “fun” ]]; then
echo “Substring found”
fi
$$
8️⃣ Changing Case (Bash 4+)
$$
word=“bash”
echo “${word^^}” # BASH (uppercase)
echo “${word,,}” # bash (lowercase)
$$
9️⃣ Trimming Whitespace
$$
str=“ hello world ”
echo “$str” # keeps spaces
echo “$(echo -e ”$str" | xargs)" # hello world
$$