Basics of Bash Scripting
Bash scripts are lines of code that are executed by the Bash shell. They are used to automate tasks and perform repetitive actions.
Scripts are stored in files with a .sh extension and can be executed by typing the path to the file in the terminal.
Make your script executable:
chmod +x myscript.sh
Run as: ./myscript.sh
Basic Syntax
First line: The shebang to indicate the interpreter this is a bash script:
#!/bin/bash
Comments start with # and are ignored by Bash:
#!/bin/bash
# This is a comment
echo "Hello, world!" # This prints a message
Variables
Variables are used to store values:
#!/bin/bash
name="John"
echo "Hello, $name!"
User Input
Read user input:
#!/bin/bash
read -p "Enter your name: " name
echo "Hello, $name!"
Bash Arrays & Associative Arrays
Declare and use arrays where each element has a numeric index (starting at 0).
# declare an array (optional)
declare -a fruits
# literal initialization
fruits=(apple banana "blood orange" kiwi)
# access by index
echo "${fruits[0]}" # apple
echo "${fruits[2]}" # blood orange
# all elements
echo "${fruits[@]}" # apple banana blood orange kiwi
# length
echo "${#fruits[@]}" # 4
# length of a single element
echo "${#fruits[2]}" # length of "blood orange" string
# append
fruits+=(mango)
- Use
${array[@]}to expand to all elements individually (good for loops). ${array[*]}expands all elements as a single word when quoted ("${array[*]}").- Always quote expansions when elements can contain whitespace:
"${arr[@]}".
Iterate through an array
# iterate values
for val in "${fruits[@]}"; do
printf '%s\n' "$val"
done
# iterate indices
for i in "${!fruits[@]}"; do
printf '%d: %s\n' "$i" "${fruits[i]}"
done
Associative arrays (hashes)
Associative arrays map string keys to values. Require Bash 4+.
# declare an associative array
declare -A user
# assign
user[name]="Ada Lovelace"
user[email]="ada@example.com"
user[lang]="Bash"
# access
echo "${user[name]}" # Ada Lovelace
# iterate keys & values
for k in "${!user[@]}"; do
echo "key=$k value=${user[$k]}"
done
# all values
echo "${user[@]}"
# check existence of a key
if [[ -v user[email] ]]; then
echo "email is set"
fi
# delete a key
unset 'user[lang]'
Important: You cannot export associative arrays to the environment. Also, associative arrays are not available in POSIX sh.
Useful Resources
Here are some useful resources to learn more about Bash scripting: