如何以编程(shell脚本),确定是否有变化? [英] How can I programmatically (in a shell script) determine whether or not there are changes?
问题描述
我想创建一个知道如果在当前工作目录更改的Bash脚本。我知道,
I am trying to create a Bash script that knows if there are changes in current working directory. I know that
$ git status
返回类似无犯的消息。什么我想,是一个变量定义为真或假。这个布尔值会告诉我,如果有还是不变化。
returns a message like "nothing to commit". What I am trying to, is to define a variable to true or false. This boolean value will tell me if there are or not changes.
显然,我不是的bash脚本的专家。我想这样的事情,
Obviously I am not an expert of bash scripts. I tried something like this,
there_are_changes=$(git status | grep nothin)
echo $there_are_changes
但预期它不工作。我应该怎么办?
but it doesn't work as expected. What should I do?
推荐答案
的git-DIFF
手册页介绍这里的相关性两种选择:
The git-diff
man page describes two options of relevance here:
--quiet
Disable all output of the program. Implies --exit-code.
和
--exit-code
Make the program exit with codes similar to diff(1). That is, it
exits with 1 if there were differences and 0 means no differences.
因此,一个强大的方法将是运行
Therefore, a robust approach would be to run
git diff --quiet; nochanges=$?
shell变量 nochanges
将等于 0
(即真)如果没有变化, 1
(即假)除外。
The shell variable nochanges
will be equal to 0
(i.e. true) if there are no changes, and 1
(i.e. false) otherwise.
您就可以使用 nochanges
的条件语句的值如下:
You can then use the value of nochanges
in conditional statements as follows:
if [ $nochanges -eq 0 ]; then
# there are no changes
else
# there are changes
fi
另外,如果你不需要存储在一个变量的退出状态,你可以这样做:
Alternatively, if you don't need to store the exit status in a variable, you can do:
if git diff --quiet; then
# there are no changes
else
# there are changes
fi
修改:由于 git的差异
是瓷的Git命令,并要以编程方式做的事情,你应该使用称为管道的Git命令 git的差异指数
代替(其中也有一个 - 安静
标志,但必须提供一个树杂交参数):
Edit: Since git diff
is a porcelain Git command and you want to do things programmatically, you should probably use the plumbing Git command called git diff-index
instead (which also has a --quiet
flag, but which must be supplied a tree-ish argument):
if git diff-index --quiet HEAD; then
# there are no changes
else
# there are changes
fi
这篇关于如何以编程(shell脚本),确定是否有变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!