1

I often accidentally perform ls on a file, when I meant to do less.

Is there a way to make an alias, or a function, that will perform ls on a directory, and less on a file.

1
  • Have a look at test. -d will check if it's argument is a directory, -f for file. So in a script could have something like if [ -f "$1" ]; then less "$1"; elif [ -d "$1" ]; then ls "$1"; fi . Although I'm sure there's mistakes there as I don't use scripts much,, just add into file, with shebang, and make executable..
    – Guy
    Jan 19, 2017 at 1:48

1 Answer 1

1

The basic thing you want might look something like this:

function my_less()
  {
  obj=$1
  shift
  test -d $obj && ls $obj $@
  test -f $obj && less $obj $@
  }

Then

my_less thing

will do an ls or a less depending on the type.

The obj=$1 grabs the first argument to the function. The shift shifts the remaining arguments "to the left" and $@ is the current argument list.

If you want to have some rudimentary processing of switches, you can extend this function something like this:

function my_less()
  {
  switches=
  obj=
  while true
  do
    case $1 in
      -*)
        switches="$switches $1"
        shift
        ;;
      *)
        obj=$1
        shift
        break
        ;;
    esac
  done
  test -d $obj && ls $switches $obj $@
  test -f $obj && less $switches $obj $@
}

This will collect all the leading switches and set obj to the first non-switch. This, will do the wrong thing frequently, but it is just a suggestion for a next step.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .