bashshellbuilt-in

What is the purpose of the : (colon) GNU Bash builtin?


What is the purpose of a command that does nothing, being little more than a comment leader, but is actually a shell builtin in and of itself?

It's slower than inserting a comment into your scripts by about 40% per call, which probably varies greatly depending on the size of the comment. The only possible reasons I can see for it are these:

# poor man's delay function
for ((x=0;x<100000;++x)) ; do : ; done

# inserting comments into string of commands
command ; command ; : we need a comment in here for some reason ; command

# an alias for `true'
while : ; do command ; done

I guess what I'm really looking for is what historical application it might have had.


Solution

  • Historically, Bourne shells didn't have true and false as built-in commands. true was instead simply aliased to :, and false to something like let 0.

    : is slightly better than true for portability to ancient Bourne-derived shells. As a simple example, consider having neither the ! pipeline operator nor the || list operator (as was the case for some ancient Bourne shells). This leaves the else clause of the if statement as the only means for branching based on exit status:

    if command; then :; else ...; fi
    

    Since if requires a non-empty then clause and comments don't count as non-empty, : serves as a no-op.

    Nowadays (that is: in a modern context) you can usually use either : or true. Both are specified by POSIX, and some find true easier to read. However there is one interesting difference: : is a so-called POSIX special built-in, whereas true is a regular built-in.