Can I get the shell to decide ls or less depending on filetype

directoryless

Very often I find myself looking through directories using 'ls', then when I find the file I want, I use 'less' to look at the file.

So for example to find a mysql log file I might type
ls /var

then:
ls /var/log/

and then:
ls /var/log/mysql

and finally:
less /var/log/mysql/mysql.log

(its a bit of a contrived example, but hopefully you know what I am doing)

I find it annoying that I need to decide if the command should be ls or less.
Why can't 'less' determine if it has been given a directory and act as 'ls' ?

Is there a command that I can use instead of less that will act as ls or less depending on the file type ? Or is there a common alias that people use ?

Best Answer

Less can determine if it has been given a directory. Set the LESSOPEN environment variable to ~/bin/LESSPIPE and make ~/bin/LESSPIPE a script like the following:

#!/bin/sh
if [ -d "$1" ]; then
  exec /bin/ls -la "$1"
elif [ -f "$1" ]; then
  case "$1" in
    *.tar|ztar) exec tar tvvf "$1" 2>/dev/null;;
    *.tar.[dg]z|*.tar.z|*.tgz) exec gzip -dc "$1" | tar tvvf - 2>/dev/null;;
    *.tar.bz2) exec bzip2 -d <"$1" 2>/dev/null | exec tar tvvf - 2>/dev/null;;
    *.tar.Z|*.taz) exec uncompress -c "$1" | exec tar tvvf - 2>/dev/null;;
    *.zip) exec unzip -l "$1" 2>/dev/null;;
    *.lha) exec lha -v "$1" 2>/dev/null;;
    *.7z) exec 7z l "$1" 2>/dev/null;;
    *.[rs]pm) exec rpm -qilp "$1";;
    *.z|*.[dg]z) exec gzip -dc "$1" 2>/dev/null;;
    *.bz2) exec bzip2 -dc "$1";;
    *.xz) exec xz -dc "$1";;
    *.Z) exec uncompress -c "$1" 2>/dev/null;;
  esac
fi

You'll get a listing for directories and archives.

You can use lesskey instead of the environment variable to set the preprocessor. See the documentation for details.