Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Speaking as a bash newbie I have been upgrading my .bashrc via copy/paste + github and I have come across the : command that stumps both me and google. e.g. : ${USER_BASH_COMPLETION_DIR:=~/.bash_completion.d}.

Without this statement originally in my .bashrc, and typing this stuff into my terminal (-> indicates relevant output):

: ${USER_BASH_COMPLETION_DIR=~/.bash_completion.d}
echo $USER_BASH_COMPLETION_DIR
-> /Users/sh/.bash_completion.d

And:

: ${USER_BASH_COMPLETION_DIR=~/.bash_completion.d}
export USER_BASH_COMPLETION_DIR=asdf
echo $USER_BASH_COMPLETION_DIR
-> asdf

But:

: ${USER_BASH_COMPLETION_DIR=~/.bash_completion.d}
export USER_BASH_COMPLETION_DIR=asdf
: ${USER_BASH_COMPLETION_DIR=~/.bash_completion.d}
echo $USER_BASH_COMPLETION_DIR
-> asdf

I don't get it!

1) How does the colon command set a variable but cannot overwrite one set by export?

2) What is the logic behind using : in some .bashrc?

Using Mac 10.6.8

(out of context include of keyword colon just to help others like me who tried to search for that term)

share|improve this question
add comment

1 Answer

up vote 6 down vote accepted

: is a shell builtin that is basically equivalent to the true command. It is often used as a no-op eg after an if statement. You can read more about it in this question from stack overflow.

The ${varname=value} basically means set the value of $varname to value if $varname is not already set, and then return the value of $varname. Though if you try to run that at the command line it will try to run the value returned. Putting the : in front as a no-op prevents bash from trying to run the value.

Note there are two slightly different forms:

${varname:=value}

sets varname to value if varname is either unset or null.

${varname=value}

only sets the value of varname if varname is currently unset (i.e., it will not change varname from "" to value)

(Thank you to chepner for clarifying that in a comment).

Someone else referencing this method

share|improve this answer
1  
${varname:=value} sets varname to value if varname is either unset or null. ${varname=value} only sets the value of varname if varname is currently unset (i.e., it will not change varname from "" to value). –  chepner May 17 '12 at 15:47
    
@chepner - thank you for that clarification - I have incorporated it into my answer. –  Hamish Downer May 24 '12 at 8:39
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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