Anatomy of my perfect ls command
Mostly notes to myself. Nestled away in my Linux Bash profile, I have this one-liner
BASHalias lh='ls -trhgGN --color=always | cut -d" " -f4-'
When I run lh
it outputs a list of files in the directory, showing their size, with the newest files on the bottom. I use this regularly to see what I've downloaded recently and how big the files are - so I made an alias.
Here's how it works.
Alias
Alias is a Jester in disguise useful Linux tool which lets you create a shortcut to a complicated command. Every flavour of Linux has a different place to store them, so do a bit of RTFM to find out where to put your commands.
ls
ls
is the standard file listing tool. It has lots of options.
-tr
sort by time in reverse order-h
human readable size format. Shows in KB, MB, GB, rather than just bytes-g
don't show the owner of the file-G
don't show the group the file belongs to-N
don't quote the file names--color=always
always colours the output, making it easier to differentiate between fields
There's no way to suppress the file permissions in ls
so we need to pipe to cut
.
cut
cut
takes a string and chops it up.
-d" "
the delimiter is the space character, cut will separate the string by the delimiter, each separated section is a field.-f4-
print the fourth field and any subsequent field
Putting it all together
"When I type lh
, please list the files in reverse time order, showing the file size but not the owners or groups, don't quote the names, and keep the colouring - then discard the first 3 columns."
Thanks to Maddison Hellstrom for the help.
Craig Heath says:
On Ubuntu Xenial, ls output seems to be missing a field you are expecting; "-f3-" on the cut does what I think you want. On cygwin the permissions field has an extra character (indicating ACLs) which is sometimes space and sometimes "+", which also messes up the cut, so for that I would go with characters rather than fields: "cut -c15-". That would mess up if a file had more than 9 links, but that never happens on cygwin. A truly portable solution is left as an exercise for the reader 😉
Craig Heath says:
Actually, on second thoughts, don't bother with cut and use "ls -shtr --color=always | cat". That seems to work find on both Ubuntu and cygwin.
Dragon Cotterill says:
I would say that there is a slight discrepancy with this command. If you have a directory that has 10 or more sub-directories then there is a slight offset as it counts the spaces. In this manner any such directory is always offset by one character and my OCD kind of winces everytime I see it.
May I suggest that the command be changed to just 'cut -b15-' as this then keeps everything straight.
Denilson says:
I have an alias with a similar purpose that I use all the time. For bonus points, the command is extremely easy to memorize even without the alias.
Shows the most recent at the bottom, shows hidden files, shows the size in human-readable format. The
--color=auto
is already part ofLS_OPTIONS
or something.