我相信命令的這部分失敗:
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