Linux – Is it possible to change the default behavior of a command

command linelinuxls

Is it possible to change the default behavior of a command?

I assume that this question is pretty straight forward but let me give an illustration and example.

While connected to some servers via SSH autocomplete via tab does not work making long commands long tedious. For example here is a ls command:

ls -lah --group-directories-first

This is saying to list all files including hidden files in a top to bottom list in a human readable format while sorting files from directories making directories come first.

Is there a way that I can configure this ls command to perform the above command by simply typing ls. By default ls list all files. There must be a place where the 'ls' command is located so that when you run it the system knows where to look to find it, see what its default behavior is, and then run it based on the specifications of the provided 'ls' command.

Ultimately can I change the output or default function of the ls command?

Best Answer

The typical way of doing this on Unix- or Linux-style systems is to use shell aliases:

alias ls='ls -lah --group-directories-first'

Note that this will overwrite any existing ls alias, so you might want to check the output of

alias ls

first and combine the above; for example

alias ls='ls -lah --group-directories-first --color=tty'

To make this permanent, add it to your .bashrc file in your home directory (assuming you’re using Bash, which you probably are if you’re discovering all this).

Altering the default behaviour in such an extensive way can end up being confusing, so I’d suggest creating a new command using an alias instead; I have

alias l='ls -lah --group-directories-first'

for example. This also allows building upon other aliases: this l alias uses whatever is defined as ls, and if that’s an alias, that gets used to (so there’s no need to repeat the --color=tty option in this case).

To remove an alias, use unalias:

unalias ls
Related Question