simple bash function does not understand git
I have git installed on my machine using homebrew as you can see below.
$ git --version
git version 1.7.3.4
I am learning bash programming and I have following function in my ~/.bashrc
function gitlab {
CMD= "git --version"
$CMD
}
However when I run gitlab开发者_C百科 I get following output
$ gitlab
-bash: git --version: command not found
I am using bash on mac.
Your problem is the space after CMD=
. This evaluates to CMD=<empty string> "git --version"
. First, the environment variable CMD
is set to an empty string, then the command git --version
is called. Notice that due to the "..."
the shell really tries to execute a command git --version
and not git
with argument --version
. Simple remove the space between =
and "
to fix this.
You are running the entire string as a single command. It is possible to have a binary called foo bar
(with a space), and you would run it just as you showed.
Edit: What are you actually trying to do? There's no need to store a command in a variable before running it:
gitlab() {git --version}
and
alias gitlab='git --version'
both do the same as you were expecting from the function above. In general, the function solution is recommended above the alias (and you don't need to prefix it with function
).
There is a superfluous space after the =
when you try to assign the string "git --version"
to the CMD
variable. The shell think this is an assignation of an empty string to the CMD
variable that is only local to the next command. As your command is quoted with "
, the shell try to execute a program called git --version
. As no such program exist, it fails.
Your function is interpreted almost like the following function (the error is easier to see here):
function() {
CMD=
"git --version"
unset -v CMD
$CMD
}
You should remove the space character to have it interpreted like you intended. However, there are easier way to do the same thing:
function gitlab() {
git --version
}
If you what you wanted was to store the result of the git --version
execution to be stored in the CMD
variable, you should have done it this way:
function gitlab() {
VERSION="$(git --version)"
echo "$VERSION"
}
Edit: corrected my reply as it was incorrect (error spotted by @DarkDust).
精彩评论