/bin/ls sorts differently than just ls
$ ls |sort
xyz-0.0.1-1554490900.rpm
xyz-0.0.1-1554745305.rpm
xyz-0.0.1-1554751021.rpm
xyz-0.0.1-1555513460.rpm
xyz-0.0.1-1555951745.rpm
xyz-0.0.1-1554323568.rpm
$ /bin/ls |sort
xyz-0.0.1-1554323568.rpm
xyz-0.0.1-1554490900.rpm
xyz-0.0.1-1554745305.rpm
xyz-0.0.1-1554751021.rpm
xyz-0.0.1-1555513460.rpm
xyz-0.0.1-1555951745.rpm
$ which ls
alias ls='/bin/ls --color'
/bin/ls
Note that the sorting is different between the two commands (ls |sort
results in incorrect sorting). This must be due to the color flag, but why?
Do:
/bin/ls --color > file1
/bin/ls > file2
and compare content, you'll see the difference.
Aliasing ls
to /bin/ls --color=auto
is likely better idea, it will stop ls
from using color codes when not writing directly to terminal (like when piping to next program or writing to a file).
In the sorted colored output ls|sort
, we can see that the last line xyz-0.0.1-1554323568.rpm
is the first line
of the non-colored output. The other lines are sorted equally.
If we have at a look at the colored escape codes (non-sorted), we can see that the first
line starts with a different escape code ^[[0m
. This is causing the wrong order when sorted (^[[01
before ^[[0m
).
$ /bin/ls --color xyz* | cat -A
^[[0m^[[01;31mxyz-0.0.1-1554323568.rpm^[[0m$
^[[01;31mxyz-0.0.1-1554490900.rpm^[[0m$
^[[01;31mxyz-0.0.1-1554745305.rpm^[[0m$
^[[01;31mxyz-0.0.1-1554751021.rpm^[[0m$
^[[01;31mxyz-0.0.1-1555513460.rpm^[[0m$
^[[01;31mxyz-0.0.1-1555951745.rpm^[[0m$