Sorting in a for loop

when i use a for loop like this,

for s in *
do
echo $s
done

it give me the result in this fashion;

1
10
12
2
23
3

I need it sorted in numerical order, like this;

1
2
3
10
12
23

Thanks in advance.

Are your filenames just numbers like: 1, 2, 23?
Otherwise what do you think you are getting with the * ?

  • makes filenames appear in alphabetic order, so I do not understand what the * is doing. Or if you are even using * the way you think you are.
for s in *
do
echo $s
done | sort -n

thanks daPeach but this dosen't work for me because i need to sort the files before start the loop.
I'm going to do more things than just echo them;

a=1
for s in *
do
echo "$s ""---"" $a"
a=$(($a+1))
done | sort -n

If i do what you tell me i get this;

1 --- 1
2 --- 4
3 --- 6
10 --- 2
12 --- 3
23 --- 5

i need...

1 --- 1
2 --- 2
3 --- 3
10 --- 4
12 --- 5
23 --- 6
a=1
for s in $(echo *|sort -n); do
  echo "$s ""---"" $((a++))"
done

The code resulted in alpha sorting, rather than numeric sorting, when I tried it.

This modification seems to produce results that are numerically sorted:

a=1
for s in $(echo * | sed 's/\W\+/\
/g ' |sort -n)
do
echo "$s ""---"" $a"
a=$(($a+1))
done

Dang you're right. I did not really check the code.
Interestingly

a=1
for s in $(ls|sort -n); do
  echo "$s ""---"" $((a++))"
done

Does work as expected...

edit:

So sort works when newline is the separator, but in the case of ls, but does or doesn't ls produce a newline?

echo *
1 10 12 2 23 3
echo *>/tmp/test1
cat /tmp/test1
1 10 12 2 23 3
ls
1  10  12  2  23  3

ls>/tmp/test2
cat /tmp/test2
1
10
12
2
23
3

Thank you guys.