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

I cannot understand this line in one of the old scripts in my project:

USER=${1:-`id -un`}
+4
source share
4 answers

This is a parameter extension pattern bash.

This statement indicates:

  • If the value $1(the first positional parameter (argument)) is not set or is equal to zero, then the command output id -unwill be set as a variableUSER

  • If the parameter is $1set and is not equal to zero, then the extension $1will be installed as a parameter USER.

, USER ​​ , , . script .

Parameter Expansion man bash, .

+4

id (man id), id -un .

:- , , , . .

, , , , $USER $1, .

+1

:

  • ${} ,
  • :- :-, ​​
  • RH

:

$ sv="set v"
$ echo ${sv:-`whoami`}
set v
$ echo ${not_set:-`whoami`}
dawg

, :

  • ${parameter:?word} , ,

    $ echo ${not_set:?'is not set to anything'}
    -bash: not_set: is not set to anything

  • ${parameter:+word} word, parameter

    $ echo ${sv:+'substitute for sv'}
     substitute for sv

  • ${parameter:=word} parameter word, parameter

    $ echo ${not_set:='now it IS set'}
    now it IS set
    $ echo "$not_set"
    now it IS set

0

USER:

USER=....

.

  • " ", ${ }.
  • $1. ${1 ... }.
  • $1 , NUL , ${1:- }.
  • $1 ( nul), .
  • $1 NUL , -.
  • - } " ".
  • .
  • id -un. , man id.
  • id -un . , .

$(id -un).

:

$ USER=${1:-$(id -un)}

USER , 1, , .

, :

$ tf(){ USER=${1:-$(id -un)}; echo "$USER"; }

If a value is specified, this value is returned:

$ tf bind
bind

If no username is specified, the name of the executable user is printed:

$ tf
bize
0
source

All Articles