9

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 '15 at 14:38
13

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 '15 at 0:57
  • What is the command alternative for OS X? – Ionică Bizău Feb 9 '15 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. – undergroundmonorail Feb 9 '15 at 16:25
9

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? – Ionică Bizău Jan 25 '15 at 16:58
  • 1
    You might instead try alias ls 'echo "Hello World!"; /usr/bin/ls' – jamesqf Jan 25 '15 at 18:19
  • 5
    @IonicăBizău any given "alias expansion rule" is only used once. – David Z Jan 25 '15 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? – Nic Hartley Jan 25 '15 at 20:42
  • @QPaysTaxes You can use & indeed but I don't get the argument you make from that. – Hauke Laging Jan 26 '15 at 1:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.