Why: prevents the $ {username = `whoami`} error?

Why

${username=`whoami`}

      

enter an error and

: ${username=`whoami`}

      

does the task without any side effects?

I understand what :

is placeholder. What is its use in this command? Is this the equivalent of a launch : 'whoami'

?


For comparison, the former use was previously called # 3 and the new one is # 4.

+3


source to share


2 answers


${parameter=value}

      

does two things: it has the side effect of being assigned value

to parameter

if parameter

not already set, and the direct effect of expanding to the value parameter

upon completion.

The error is the result of this direct effect: on startup

${user=`whoami`}

      

... on its own line, then it expands and tries to run the output whoami

as a command. Let's say that a custom variable has not been previously assigned and the output whoami

is james

; it would try to run the command james

, which would throw an error.



In contrast,

: ${user=`whoami`}

      

... does the side effect first (run the job user

if user

not already set) and then runs:

: james

      

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

+6


source


In # 3, according to the bash man pages, you are trying to execute the output of the whoami command, i.e. if the output of the whoami command is "peter", # 3 means the "peter" command is invoked. In addition, the variable "username" is assigned the value "peter"

The bash manual describes it ${parameter:=word}

like this:

Assign default values. If no parameter is specified or null, the word extension is assigned to the parameter. The parameter value is then replaced. Therefore, you cannot assign positional parameters and special parameters.



Likewise, for the command :

-

No effect; the command does nothing outside of expanding the arguments and performing any given redirections. A zero return code is returned.

+3


source







All Articles