A nice ls alias
Here's a nice "ls" alias for .bashrc
# alias for ls
lss() {
ls -ald --color "$@" | less -RFX
}
^ Edited to quote the arguments "$@"
With the arguments quoted the "No such file or directory" error gets cut off.
$ lss *blah*
quoted
: No such file or directory
not quoted
ls: cannot access '*blah*': No such file or directory
But, overall it works better if you're passing quotes.
$ lss "test file.txt"
quoted
-rw-rw-r-- 1 david david 5 Oct 8 12:39 test file.txt
not quoted
ls: cannot access 'test': No such file or directory
ls: cannot access 'file.txt': No such file or directory
Tagged:



Comments
Ugh, after testing various arguments I forgot to test it without.
This works better.
ls -d is helpful when passing a wildcard, so the directory names are listed instead of recursing into directories, but without any arguments it just lists the home directory.
Small improvement: [[ "$@ == " ]] can misbehave with several arguments. Checking the argument count is more robust:
lss() {
if (( $# )); then
ls -ald --color "$@" | less -RFX
else
ls -al --color | less -RFX
fi
}
I find that doesn't quite work, since $# still has a value with no arguments, so it always gets the first option. But this works:
Thanks.
Huge difference between parenthesis and brackets.
Also, when using brackets, variables should either be quoted
"$var"or expanded with braces${var}.Ah, didn't catch that.
didn't catch that
Thank you for this, david3. As someone still learning Linux on my first VPS, the part about quoting "$@" was the most useful bit for me, because I had not thought about how a file name with a space could break a simple alias. I also had not realised ls -d stops a directory name from expanding into its contents. Do you keep this kind of helper in .bashrc on every server, or do you only add it once you find yourself typing the same long ls command often?
@david3 FinCoder's
(( $# ))version should actually work: with no arguments$#is 0, and(( 0 ))is false, so it takes the else branch. If it kept taking the first branch for you, there was probably an olderlssstill loaded in that shell (type lssshows which definition bash is using). One more small tweak: ls writes errors to stderr, which isn't piped into less, so adding2>&1before the pipe keeps the "No such file or directory" message inside the pager instead of it getting mangled.@natboxio
Yes, I missed the parenthesis vs. brackets () []. Either of these should work.
I don't find the redirection "2>&1" helps, though. Sometimes errors are cut off; seems random.