- #1
- 2,147
- 2,719
Disclaimer: I am an absolute beginner in bash scripting.
I spent the whole evening trying to make this code snippet work as intended. The program is supposed to sort an array using bubble sort algorithm.
I knew the algorithm well; the only problem I faced was brackets. Curly brackets, parenthesis, square brackets — all got mixed up. Later, I found this question on Stack Overflow that outlines the different brackets and their meanings. That solves most of the queries, but some remain:
I spent the whole evening trying to make this code snippet work as intended. The program is supposed to sort an array using bubble sort algorithm.
Program:
#!/bin/bash
arr=(7 -1 9 2 11 -13 5)
for (( i=0; i<(( ${#arr[@]} - 1 )); i++ )) ; do
for (( j=0; j<(( ${#arr[@]} - 1 - i )); j++ )); do
if (( arr[j] > arr[j+1] )); then
temp=${arr[j]}
arr[j]=${arr[j+1]}
arr[j+1]=${temp}
fi
done
done
echo -ne "\n"
printf '%s\n' "${arr[@]}"
Output:
-13
-1
2
5
7
9
11
- Square brackets,
[[...]]
are used for logical expressions. Then why does neitherif [[ arr[j] > arr[j+1] ]]
norif [[ ${arr[j]} > ${arr[j+1]} ]]
work? (On the other hand, bothif (( ${arr[j]} > ${arr[j+1]} ))
andif (( arr[j] > arr[j+1] ))
works.) - I found that I get the correct output even if I don't use
$
in front ofi
andj
. If bash can substitute the value of the variable here, why can't it do the same in other places? (For example, in lines 8, 9 and 10, I have to use${...}
on the RHS of the=
operator.)