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.
${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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With