I'm trying to sort directory list in reverse alphabetical order.
Why do I get a random order ?
ls -l /usr/bin/ | sort -r
Edit : I'm obliged to use the command sort.
Let ls do the sorting:
ls -l -r /usr/bin
or just
ls -lr /usr/bin
The standard -r option to ls make it sort the list in the reverse order to what it would otherwise do. If you ask ls to sort on the modification timestamp with -t, -r will reverse the order of that list too, etc.
Your command pipeline sorts on the permissions, ownership, etc. that ls -l outputs, and would not consider the filenames unless all other information for two entries were identical.
You did not ask about this, but since it's a common thing to want to do and often the next step after asking about ls output ordering... To actually extract the filenames sorting first or last from a directory listing, don't use ls, instead use an array or the positional parameters:
The first filename:
names=(/usr/bin/*)
printf '%s\n' "${names[0]}"
or
set -- /usr/bin/*
printf '%s\n' "$1"
The last filename:
names=(/usr/bin/*)
printf '%s\n' "${names[-1]}"
or
set -- /usr/bin/*
shift "$(( $# - 1 ))"
printf '%s\n' "$1"
Likewise, the best way to get the most recently modified file (or directory) in bash would be to do
set -- /usr/bin/*
newest=$1; shift
for pathname do
[ "$pathname" -nt "$newest" ] && newest=$pathname
done
printf 'Newest: %s\n' "$newest"
Change the -nt test to -ot to get the oldest (least recently modified) file.
You are trying to sort using the entire string as a key.
The object names are written in the 9th column, so it is necessary to use:
ls -l /usr/bin/ | sort -k9 -r
ls also outputs a line saying total, followed by a number. This solution seems to ignore that line and will likely output it last rather than first. It would make more sense to use ls -l /usr/bin | tac as it would be quicker to type (the final output might be different unless you're in the POSIX locale though).