Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this bash mean: USER=${1:-`id -un`}

Tags:

bash

I can not understand this line in one of old scripts in my project :

USER=${1:-`id -un`}
like image 913
Sean Lin Avatar asked Jan 07 '23 07:01

Sean Lin


2 Answers

It's a bash parameter expansion pattern.

The given statement indicates:

  • If the value of $1 (the first positional parameter (argument)) is unset or null then the output of the command id -un will be set as variable USER

  • If the parameter $1 is set and not null then the expansion of $1 will be set as parameter USER.

Also the variable USER should be set session wide upon login, unless you have a very good reason you should not modify it directly. You can use a different variable name in your script as a solution then.

Check the Parameter Expansion section of man bash to get more idea.

like image 173
heemayl Avatar answered Jan 14 '23 19:01

heemayl


Looking at the manual page for id (man id), the command id -un will return the actual name of the user.

The format :- uses what's on the right only if what's on the left isn't set. More can be learned about this syntax here.

Therefore, the code you provided is essentially saying default to user, but override the $USER variable to the value of $1 if it is provided.

like image 38
drewyupdrew Avatar answered Jan 14 '23 20:01

drewyupdrew