Question about sorting -- how to pass an array to a function

Hi, guys

I just wanted to sort the elements of an array ascendingly.
I know the following code does work well:

array=(13 435 8 23 100)
for i in {0..4}
do
	j=$((i+1))
	while [[ $j -le 4]]
	do
		if [[ ${array[$i]} -le ${array[$j]} ]]
		then :
		else
			min=${array[$j]}
			${array[$j]}=${array[$i]}
			${array[$i]}=$min
		fi
		((j++))
	done
done

However, I wanted to write a function named "sort" and pass the array as argument to the function.
I know the following code doesn't work:

array=(13 435 8 23 100)
sort()
{
for i in {0..4}
do
	j=$((i+1))
	while [[ $j -le 4]]
	do
		if [[ ${$1[$i]} -le ${$1[$j]} ]]
		then :
		else
			min=${$1[$j]}
			${$1[$j]}=${$1[$i]}
			${$1[$i]}=$min
		fi
	done
done
}
sort array

And I know it'll be better by using the command "eval" to pass the array to the function like this:

eval first_num=\${$1[$i]} 

but I can't put it to the correct place in the function.
So please give me some ideas~~ Thx

Using eval means you can pass names as string parameters, put that string into a command string, and eval theat command string to get the shell to re-parse it as script. For instance:

pick_an_arg(){
  arg_no=$1
  shift
  eval 'echo "$'"$arg_no"'"'
 }

lets you print the fourth arg using arguments: 3 ? ? fourth_arg ? ? ? ?

Be very very careful using eval, however. It will parse any valid shell syntax it finds -- including things you might not have intended, such as string contents. Someone putting `rm -Rf ~/` into your array could be very bad.

So how about my question? How to pass the array as argument to the function?
:):slight_smile:

You've been given the answer. Pass the array name into the function, assemble the statement you want as text in a string, then use eval to parse that text as a shell statement (since shell will not do that kind of double-think unless you ask).

Quoting of anything going into eval is helpful, and if the input is human, maybe a check for meta-characters. It is very like preventing a SQL Injection attack (which were allowed by sloppy SQL tool choices).