I have a problem regarding about the syntax on how to swap the element value in an array.
array="5 3 2 1 4"
echo "${array[*]}"
changed=1
while [ $changed != 0 ]
do
changed=0
for (( i=0 ; i<=${#array[@]}-1 ; i++ ))
do
if [ ${array[$i]} -gt ${array[$i+1]} ]
then
tmp=${array[$i]}
array[$i]=${array[$i+1]}
array[$i+1]=$tmp
changed=1
fi
done
done
echo "Sorted array: "
echo "${array[*]}"
Edit:
Thanks for answering my question. I have changed the code, and now and it looks something like this.
But unfortunately there is still a problem.
It says:
jdoodle.sh: line 3: $'\r': command not found
jdoodle.sh: line 8: syntax error near unexpected token `$'\r''
jdoodle.sh: line 8: ` for ((i=0;i<=${#array[@]}-1;i++))
((...integer math...))is the preferred method,$((...integer math...))for the result itself (letandexprwork, but have limitations by comparison). Note:for (( i=0 ; i<${#array[@]}; i++ ))and for indexed arrays${array[i]}is sufficient in bash. But for arithmetic within the index$((i+1))is the best choice.=in assignments.\r\n) as end of line; Linux and Unix use only\n. Seeman dos2unix.