Let's say I want to modify the original behavior of the ls tool this way:

$ ls
Hello World
file1 file2 ...

How can I do this?

When running ls I would like to run another command let's say echo "Hello World!".

The quick solution I see is using alias:

alias orig_ls="ls"
alias ls='echo "Hello World!"'

However, this is not a real solution since when I will run orig_ls it will output "Hello World!".

  • Put another ls in the users own path and use this to hook the original.
    – peterh
    Jan 25, 2015 at 14:38

2 Answers 2


Sometimes an alias isn't powerful enough to easily do what you want, so here's a way without using them.

In some file that is sourced when your shell starts (e.g. .bashrc), add the following function:

ls () {
    echo "Hello world!"
    command ls "$@"

Unlike an alias, a function can recurse. That's why command ls is used instead of ls; it tells your shell to use the actual ls instead of the function you've just defined.

  • 2
    Indeed. This solution scales better. +1
    – PythonNut
    Jan 26, 2015 at 0:57
  • What is the command alternative for OS X? Feb 9, 2015 at 16:21
  • @IonicăBizău I have no idea command didn't work :/ I have no idea and I don't have a Mac with which to test it, sorry. Feb 9, 2015 at 16:25

You must not forget to call ls:

alias ls='echo "Hello World!"; ls'
  • Ha! I supposed this will create an infinite cycle! But why doesn't it create an infinite loop? Jan 25, 2015 at 16:58
  • 1
    You might instead try alias ls 'echo "Hello World!"; /usr/bin/ls'
    – jamesqf
    Jan 25, 2015 at 18:19
  • 6
    @IonicăBizău any given "alias expansion rule" is only used once.
    – David Z
    Jan 25, 2015 at 19:53
  • Would joining the two with an & also work? That would also ensure that the user's command is only run if the custom one works, right?
    – anon
    Jan 25, 2015 at 20:42
  • @QPaysTaxes You can use & indeed but I don't get the argument you make from that. Jan 26, 2015 at 1:02

You must log in to answer this question.

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