Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the ":" command?

Tags:

bash

shell

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?

like image 562
q0987 Avatar asked Jan 24 '26 08:01

q0987


2 Answers

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.

like image 154
Mikel Avatar answered Jan 27 '26 00:01

Mikel


I suppose what the man page writers meant was

: ${var:=value}

Can be used as a short cut instead of say

if [ -z "$var" ]; then
    var=value
fi
like image 34
sehe Avatar answered Jan 27 '26 01:01

sehe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!