A nice ls alias

edited October 8 in Technical

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.

    # alias for ls
    lss() {
      if [[ "$@" == "" ]]
      then
        ls -al --color "$@" | less -RFX
      else
        ls -ald --color "$@" | less -RFX
      fi
    }
    

    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:

    # alias for ls
    lss() {
      if [[ $# -eq 0 ]]
      then
        ls -al --color "$@" | less -RFXE
      else
        ls -ald --color "$@" | less -RFXE
      fi
    }
    

    Thanks.

  • edited October 27

    Huge difference between parenthesis and brackets.

    echo "testing [[ ]]"
    if [[ "0" ]]
    then
      echo "0 as a string is true"
    fi
    echo "testing (( ))"
    if (( 0 ))
    then
      echo "0 as a number is true"
    else
      echo "0 as a number is false"
    fi
    

    Also, when using brackets, variables should either be quoted "$var" or expanded with braces ${var}.

  • Ah, didn't catch that.

  • XiaoBiXiongXiaoBiXiong New Member

    didn't catch that

    Flagged for moderation (1)
Sign In or Register to comment.