GoTTimw
GoTTimw

Reputation: 2430

Linux alias chain commands (can recursion be avoided?)

I've been looking around for ways to alias clear and ls into one command. Currently I've defined command x:

alias x="clear;ls"

Now is there any walkaround to avoid recursion and define:

 alias ls='clear;ls'

Upvotes: 19

Views: 8939

Answers (5)

ShpielMeister
ShpielMeister

Reputation: 1455

There is no direct recursion in alias. From man bash:

The first word of the replacement text is tested for aliases, but a word that is identical to an alias being expanded is not expanded a second time. This means that one may alias ls to ls -F, for instance, and bash does not try to recursively expand the replacement text.

Nonetheless, you can also note:

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.

$ pwd
/Users/myhomedir

$ alias ls="date;pwd"
$ ls
Fri Jun 23 16:34:00 PDT 2023
/Users/myhomedir


$ alias pwd='whoami'
$ ls
Fri Jun 23 16:35:00 PDT 2023
enzyme

$ alias ls="date;'pwd'"
$ ls
Fri Jun 23 16:35:38 PDT 2023
/Users/myhomedir

Upvotes: 3

alper
alper

Reputation: 3410

I always use ls with --color=auto parameter ( -G Enable colorized output.) and like to use functions.

clear_and_ls() {
    clear
    command ls --color=auto
}

alias ls="clear_and_ls"

Upvotes: 0

Jonathan
Jonathan

Reputation: 1233

If you put a backslash before the command name, that will disable any aliases.

alias ls='clear;\ls'

Or, like Arnaud said, just use the full path for ls.

Upvotes: 39

jpalecek
jpalecek

Reputation: 47770

Another way of doing this would be

alias ls='clear; command ls'

This is different from /usr/bin/ls, as it still searches ls in the $PATH, but will ignore shell functions or aliases.

Upvotes: 20

Arnaud F.
Arnaud F.

Reputation: 8462

Just do :

alias ls='clear;/usr/bin/ls'

When typing:

$ ls

First of all it will search an user defined function, it will launch it, else search in $PATH commands.

By giving the explicit path of the ls command, recursion will be avoided.

Upvotes: 1

Related Questions