0

I have a variable that may or may not be empty. If it's not empty, I want that value. If it is empty, I want the value of some other command. Example:

my_function ()
{
    name_override="$1"
    user_name=${name_override} || $(git config "user.name")
}

I'm not sure if the code above will work. But basically I want to run git config and store that result in user_name if the name_override variable is unset (and thus $1 would not have been provided).

How can I do this correctly?

void.pointer
  • 24,859
  • 31
  • 132
  • 243
  • 1
    possible duplicate of [Assigning default values to shell variables with a single command in bash](http://stackoverflow.com/questions/2013547/assigning-default-values-to-shell-variables-with-a-single-command-in-bash) – Tom Fenech Sep 21 '14 at 16:54
  • @TomFenech Thanks that does answer my question. I did search prior to posting but I did not find that. – void.pointer Sep 21 '14 at 16:56
  • No problem, glad your problem is solved either way. – Tom Fenech Sep 21 '14 at 16:57

1 Answers1

1

The bash idiom for accomplishing this is

user_name=${1:-$(git config "user.name")}

where :- says to use the value of $1 if it is set and non-null, else use the following string.

chepner
  • 497,756
  • 71
  • 530
  • 681