Reputation: 41
I can not understand this line in one of old scripts in my project :
USER=${1:-`id -un`}
Upvotes: 4
Views: 3252
Reputation:
That line is setting the value of a variable called USER
:
USER=....
The right side of the equal has several levels.
${ }
.$1
. That's why it is ${1 ... }
.$1
is being tested if it is NUL
or unset, the ${1:- }
.$1
is NUL
or unset, substitute the value at the rigth of the -
.-
and the }
is a "command substitution".id -un
. You can understand what it does with man id
.id -un
prints a name. The current user if user is omitted.The same command could be executed by $(id -un)
.
That would change the line to this:
$ USER=${1:-$(id -un)}
Which will set USER to the name given as positional parameter 1
or the name of the current user executing the line.
To try it, you can make a function:
$ tf(){ USER=${1:-$(id -un)}; echo "$USER"; }
If an value is given, that value is printed back:
$ tf bind
bind
If a user-name is not given, the executing user name is printed:
$ tf
bize
Upvotes: 1
Reputation: 1609
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.
Upvotes: 2
Reputation: 104015
Parse it this way:
${}
tells you it is a parameter expansion:-
is use a default value of the Right Hand of the :-
if the Left Hand is unsetExample:
$ sv="set v"
$ echo ${sv:-`whoami`}
set v
$ echo ${not_set:-`whoami`}
dawg
There are other forms, including:
${parameter:?word}
display an error if the parameter is unset,
$ echo ${not_set:?'is not set to anything'}
-bash: not_set: is not set to anything
${parameter:+word}
substitute value of word
only if parameter
is set
$ echo ${sv:+'substitute for sv'}
substitute for sv
${parameter:=word}
assign parameter
the value of word
if parameter
is unset
$ echo ${not_set:='now it IS set'}
now it IS set
$ echo "$not_set"
now it IS set
Upvotes: 1
Reputation: 42087
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.
Upvotes: 5