0

This question already has an answer here:

I need to set a variable in my bash script

#!/usr/bin/env bash

GITNAME= git config --global user.name
echo " $GITNAME "

But it doesn't seems to work that way.

How does it work?

marked as duplicate by Gilles bash Aug 2 '16 at 23:09

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • GITNAME="git config --global user.name" or GITNAME='git config --global user.name'you need to enclose it in quotes, because it has spaces in it. – MelBurslan Aug 2 '16 at 14:40
  • Remove the space after =, otherwise the shell interprets this as a call to git with empty GITNAME. – countermode Aug 2 '16 at 15:06
6

Assuming you're trying to execute the git command and store its result in a variable you'll want the $(...) syntax, where you put your command inside the parens:

GITNAME="$(git config --global user.name)"
printf '%s\n' "$GITNAME"

note also that there is no space after the = in the assignment. As sjsam pointed out, it's best to quote around the parens too. That's because after command substitution word splitting and glob expansion and several other parsing steps still happen, so if your name contained, say * the glob would be expanded, and that's probably not what you intend.

As a style note, you should generally not use all upper case for your variable names, as that could cause them to collide with environment variables.

6

Couple of suggestions

What is wrong with below

GITNAME= git config --global user.name
  • Don't use full-uppercase variables for your script as they might conflict with a system variable with similar name
  • There should not be spaces around = in the form variable=value
  • In your case the right hand side is an expression so you need to wrap it in backticks (``) which tells the shell that it encloses a command and should be substituted with the result.
  • Now, backticks are legacy, you can use [ more capable ] $() instead of them.
  • Finally double quote the command substitution to prevent [ word splitting ].

Corrected statement

gitname="$(git config --global user.name)" # Error proof
3

To save the output of a command as variable in bash, use command substitution $():

GITNAME="$(git config --global user.name)"

Note that, in bash, there must not be any whitespace around = in variable declaration.

Also, be careful with the uppercase variable naming as it can replace any environment variable (which are upper cased usually) with the same name. Unless absolutely necessary use lowercase characters for user defined variables.

On the other hand, if you just need to save the string as a variable:

GITNAME="git config --global user.name"
  • Clearly he is intending to do command substitution. – sjsam Aug 2 '16 at 15:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.