bashshell

What is the ":" command?


The colon command is a null command.

The : construct is also useful in the conditional setting of variables. For example,

: ${var:=value}

Without the :, the shell would try to evaluate $var as a command.

I don't quite understand the last sentence in above statement. Can anyone give me some details?


Solution

  • Try

    var=badcommand
    $var
    

    you will get

    bash: badcommand: command not found
    

    Try

    var=
    ${var:=badcommand}
    

    and you will get the same.

    The shell (e.g. bash) always tries to run the first word on each command line as a command, even after doing variable expansion.

    The only exception to this is

    var=value
    

    which the shell treats specially.

    The trick in the example you provide is that ${var:=value} works anywhere on a command line, e.g.

    # set newvar to somevalue if it isn't already set
    echo ${newvar:=somevalue}
    # show that newvar has been set by the above command
    echo $newvar
    

    But we don't really even want to echo the value, so we want something better than
    echo ${newvar:=somevalue}.

    The : command lets us do the assignment without any other action.