Reputation: 1511
I'm new to bash and having some issues printing out individual numbers after sorting an array. I have the following....
for x in ${array[@]}
do
echo $x
done| sort
This is the only way I was able to print out the entire array in order. Now I'm trying to print out a single item after it's been ordered so I tried....
for x in ${array[@]}
do
echo ${array[2]}
exit
done| sort
But it prints the third item in the unordered array array instead. Any help?
Upvotes: 1
Views: 36
Reputation: 2337
You are printing the variable and then trying to sort the ONLY variable that you have printed (in your case ${array[2]}
)
Try this:
sorted=($(printf '%s\n' "${array[@]}"|sort))
echo ${sorted[2]}
This sorts the array and stores it in another array sorted
Upvotes: 1