Search code examples
linuxbashfunctionamazon-ec2cd

Why might cd call the function ':'?


I am using Ubuntu (Amazon EC2), and when I type cd, this happens:

$ cd
hi
hi
hi
hi
hi
hi
hi
hi
hi
$

I had previously made : be a function: : () { echo hi; }

This happens in the top-level shell $SHLVL=1, but not in any subshell (typing bash then trying to reproduce this does not work).

Does anyone know why this may be happening?


Solution

  • What you did is a very poor idea because : is the shell null command.

    It is useful from time to time in constructs that require a command. For instance, if you want code an infinite loop using while, it helps:

    while true ; do
      :
    done
    

    Take out the : and it's not well-formed any more: do requires a command. Out of the following three one-liners, only the last one is correct—try them:

    while true do done
    while true do ; done
    while true do : ; done
    

    If you redefine : as a function, a good question is: is that well defined? But never mind that, suppose it works. Suddenly, these occurrences of : that crop up in scripts from time to time will be calling your function!

    What is cd in the Amazon EC2 shell environment? Maybe it's a function. Type set and browse through the output. I've often defined a custom cd function; it's useful to do. You can do things like dynamically update the prompt and window title and whatnot.