How to use spaces in a bash alias name?

The Bash documentation states "For almost every purpose, shell functions are preferred over aliases." Here is a shell function that replaces ls and causes output to be piped to more if the argument consists of (only) -la.

ls() {
    if [[ $@ == "-la" ]]; then
        command ls -la | more
    else
        command ls "$@"
    fi
}

As a one-liner:

ls() { if [[ $@ == "-la" ]]; then command ls -la | more; else command ls "$@"; fi; }

Automatically pipe output:

ls -la

From the alias man page:

The first word of each simple command, if unquoted, is checked to see if it has an alias. If so, that word is replaced by the text of the alias. The alias name and the replacement text may contain any valid shell input, including shell metacharacters, with the exception that the alias name may not contain `='.

So, only the first word is checked for alias matches which makes multi-word aliases impossible. You may be able to write a shell script which checks the arguments and calls your command if they match and otherwise just calls the normal ls (See @Dennis Williamson's answer)


A slightly improved approach taken from Dennis' answer:

function ls() {
  case $* in
    -la* ) shift 1; command ls -la "$@" | more ;;
    * ) command ls "$@" ;;
  esac
}

Or the one-liner:

function ls() { case $* in -la* ) shift 1; command ls -la "$@" | more ;; * ) command ls "$@" ;; esac }

This allows for further options/arguments to be appended after the command if needed, for example ls -la -h

Tags:

Unix

Bash

Alias