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?
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?
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.
Couple of suggestions
What is wrong with below
GITNAME= git config --global user.name
=
in the form variable=value
$()
instead of them.Corrected statement
gitname="$(git config --global user.name)" # Error proof
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"
GITNAME="git config --global user.name"
orGITNAME='git config --global user.name'
you need to enclose it in quotes, because it has spaces in it. – MelBurslan Aug 02 '16 at 14:40=
, otherwise the shell interprets this as a call to git with emptyGITNAME
. – countermode Aug 02 '16 at 15:06