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?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
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
$()instead of them.
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"