Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does : prevent ${username=`whoami`} from throwing an error?

Tags:

bash

shell

Why does

${username=`whoami`}

throw an error, whereas

: ${username=`whoami`}

performs an assignment without any ill effects?

I understand : is a placeholder. What is its use in this command? Is it the equivalent of running : 'whoami'?


For reference, the former usage was previously referred to as #3, and the new one as #4.

like image 782
imagineerThat Avatar asked Feb 10 '26 22:02

imagineerThat


1 Answers

${parameter=value}

does two things: It has the side effect of assigning value to parameter if parameter is not already set, and the direct effect of expanding to the value of parameter when complete.

The error is the result of that direct effect: When you run

${user=`whoami`}

...on its own line, then that expands to, and tries to run, the output of whoami as a command. Let's say that the user variable is not previously assigned to, and the output of whoami is james; it would then try to run the command james, which would throw an error.

By contrast, running

: ${user=`whoami`}

...first performs the side effect (of doing an assignment to user if user is not already set), and then runs:

: james

...which has no effect, so only the side effect (of the assignment) is performed.

like image 153
Charles Duffy Avatar answered Feb 13 '26 13:02

Charles Duffy



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!