19

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'
knittl
  • 246,190
  • 53
  • 318
  • 364
GoTTimw
  • 2,330
  • 6
  • 26
  • 34
  • I can't get it to do anything recursive on my system, but have you tried `alias ls='clear;/bin/ls'`? – Manny D Oct 10 '11 at 16:42
  • 2
    My `ls` has long been an alias referring to 'ls' and, like Manny D, it's never had recursion problems. I tried your `alias ls='clear;ls'` and it worked fine also. This is on RHEL 5 Linux, with Bash version 3.2.25 -- what kind of system and what shell are you using? – Stephen P Oct 10 '11 at 16:55
  • oh I was using tcsh, if I define: alias ls `'clear;ls'` and use ls it will throw an `"Alias Loop."` error. But it worked under Bash. – GoTTimw Oct 10 '11 at 17:06
  • Perhaps you should change the `bash` flag to `tcsh` then. – Garrett Oct 06 '14 at 04:19

5 Answers5

36

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.

Jonathan
  • 1,163
  • 7
  • 12
20

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.

jpalecek
  • 47,058
  • 7
  • 102
  • 144
  • 1
    This is applicable to many situations, not just aliases. If you want to go straight to built-ins and executables, bypassing functions and aliases, use the `command` built-in. – Zenexer Aug 04 '13 at 06:51
3

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
ShpielMeister
  • 1,417
  • 10
  • 23
1

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.

Arnaud F.
  • 8,252
  • 11
  • 53
  • 102
0

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"
alper
  • 2,919
  • 9
  • 53
  • 102