我相信命令的这部分失败:
echo "my first string" | git hash-object -w --stdin
有没有解决这个办法,以便它可以一个git 目录外被执行?
您所遇到的问题是因为你传递给git hash-object
命令-w
选项。该选项需要现有的存储库,因为它具有writing the object into the git database的副作用。
证明:
$ echo "my first string" | git hash-object -w --stdin
fatal: Not a git repository (or any parent up to mount point /home)
Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).
$ echo "my first string" | git hash-object --stdin
3616fdee3ac48e5db02fbf9d5e1c2941cfa3e165
然而,由于你的最终目标是获得,如果你想用的git hash-object
帮助做到这一点,你必须有一个Git仓库的git diff
两者给出的字符串。为此,你可以生成一个临时的空库:
$ tmpgitrepo="$(mktemp -d)"
$ git init "$tmpgitrepo"
Initialized empty Git repository in /tmp/tmp.MqBqDI1ytM/.git/
$ (export GIT_DIR="$tmpgitrepo"/.git; git diff $(echo "my first string" | git hash-object -w --stdin) $(echo "my second string" | git hash-object -w --stdin) --word-diff)
diff --git a/3616fdee3ac48e5db02fbf9d5e1c2941cfa3e165 b/2ab8560d75d92363c8cb128fb70b615129c63371
index 3616fde..2ab8560 100644
--- a/3616fdee3ac48e5db02fbf9d5e1c2941cfa3e165
+++ b/2ab8560d75d92363c8cb128fb70b615129c63371
@@ -1 +1 @@
my [-first-]{+second+} string
$ rm -rf "$tmpgitrepo"
这种方法可以打包成一个bash函数:
git-diff-strings()
(
local tmpgitrepo="$(mktemp -d)"
trap "rm -rf $tmpgitrepo" EXIT
git init "$tmpgitrepo" &> /dev/null
export GIT_DIR="$tmpgitrepo"/.git
local s1="$1"
local s2="$2"
shift 2
git diff $(git hash-object -w --stdin <<< "$s1") $(git hash-object -w --stdin <<< "$s2") "[email protected]"
)
使用:
git-diff-strings <string1> <string2> [git-diff-options]
例:
git-diff-strings "first string" "second string" --word-diff
注意,您可以git diff
两个字符串通过创建包含这些字符串,在这种情况下,你不需要一个Git仓库2个临时文件。
这似乎解决您的问题:https://stackoverflow.com/questions/7149984/how-do-i-execute-a-git-command-without-being-on-the-repository-folder?noredirect= 1 – jburtondev
谢谢你的抬头...如果我的代码在无数其他机器上执行,有没有办法可靠地设置 - git-dir? – danday74