我相信这部分命令失败了:
echo "my first string" | git hash-object -w --stdin
有没有办法解决这个问题,以便它可以在 git 目录之外执行?
您遇到的问题是因为-w
您传递给git hash-object
命令的选项。该选项需要一个现有的存储库,因为它具有将对象写入 git 数据库的副作用。
证明:
$ 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 diff
两个给定字符串之间的值,因此如果您想在git hash-object
1的帮助下完成此操作,则必须拥有一个 git 存储库。为此,您可以生成一个临时的空存储库:
$ 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") "$@"
)
用法:
git-diff-strings <string1> <string2> [git-diff-options]
示例:
git-diff-strings "first string" "second string" --word-diff
1请注意,您可以git diff
通过创建 2 个包含这些字符串的临时文件来创建两个字符串,在这种情况下,您不需要 git 存储库。