for Loops: Once per Item
A for loop runs its body once for each word in a list, which can come from an array, arguments, a file pattern, a brace range or an arithmetic counter.
Iterate over intact arguments or array elements and inspect each iteration's value.
backup.sh should now make one archive per folder, so a broken photo folder does not spoil the notes backup. Writing the tar line three times would work until someone adds a fourth folder. A for loop runs the same body once for each item, however many there are.
The rule
for name in list; do body; done: the body runs once per word.
for dir in "${dirs[@]}"; do
name="${dir##*/}"
tar -czf "$dest/${name// /_}-$stamp.tar.gz" "$dir"
echo "Packed $dir"
doneOn each pass, dir holds the next item, then the body runs. The list can come from many places:
for dir in "${dirs[@]}"; do ... # an array
for dir in "$@"; do ... # the script's arguments
for dir; do ... # short for: in "$@"
for f in "$dest"/*.tar.gz; do ... # files matching a pattern
for n in {1..5}; do ... # a brace range: 1 2 3 4 5
for (( i = 0; i < 3; i++ )); do ... # a counter: 0 1 2The file pattern form is the safe way to loop over files: each matching name arrives whole, spaces and all. Avoid for f in $(ls): the output of ls is split on spaces, so My Notes.txt becomes two items. One more surprise: if a pattern matches nothing, the loop runs once with the pattern itself, such as the literal text *.log. Guard with [[ -e "$f" ]] || continue.