我在 Bash 中有兩個函式。一個是通用運行函式,它接受輸入并對其進行評估,同時列印命令并測驗退出代碼。這在大型腳本中使用,以確保每個命令在繼續之前成功執行。
第二個是一個復雜的功能,就是做一些 Git 歷史決議。有問題的行是唯一顯示的行。
我從一個 for 回圈中呼叫這個函式,它遍歷要搜索的術語串列。問題是在其他單詞之間沒有正確處理空格。我嘗試通過 shell 檢查網站運行我的腳本,所有建議似乎都破壞了我的代碼。
function run() {
echo "> ${1}"
eval "${1}"
# Test exit code of the eval, and exit if non-zero
}
function searchCommitContents() {
run 'result=$(git log -S'"${1}"' --format=format:%H)'
# Do something with result, which is a list of matching SHA1 hashes for the commits
echo "${result}"
}
# Main
declare -a searchContents=('foo' 'bar' ' foo ' 'foo bar')
for i in "${searchContents[@]}"
do
searchCommitContents "${i}"
done
這是我得到的輸出:
> result=$(git log -Sfoo --format=format:%H)
<results>
> result=$(git log -Sbar --format=format:%H)
<results>
> result=$(git log -S foo --format=format:%H)
<results>
> result=$(git log -Sfoo bar --format=format:%H)
fatal: ambiguous argument 'bar': unknown revision of path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
我嘗試在代碼的各個區域添加額外的單引號和雙引號,這樣'foo bar'字串就不會決議為兩個不同的單詞。我還嘗試在美元符號上添加轉義符,如下所示:-s'"\${1}"'基于此站點上的其他問題。
uj5u.com熱心網友回復:
你為什么要列印result=$(?它是一個內部變數,它可以是任何東西,在日志中不需要它。
列印您正在執行的命令,而不是變數名。
run() {
echo " $*" >&2
"$@"
}
searchCommitContents() {
local result
result=$(run git log -s"${1}" --format=format:%H)
: do stuff to "${result}"
echo "$result"
}
輸入中間有空格的問題。
如果您想要參考字串,請使用printf "%q"或${...@Q}用于更新的 Bash,但我不太喜歡這兩種參考方法,只使用$*. 我真的很喜歡/bin/printfGNU coreutils,但它是一個單獨的程序......雖然${..@Q}是最快的,但它(仍然)對我來說不夠便攜(我有一些舊的 Bash)。
# compare
$ set -- a 'b c' d
$ echo " $*" >&2
a b c d
$ echo " $(printf " %q" "$@")" >&2
a b\ \ c d
$ echo " " "${@@Q}" >&2
'a' 'b c' 'd'
$ echo " $(/bin/printf " %q" "$@")" >&2
a 'b c' d
uj5u.com熱心網友回復:
請參閱這些行:
> result=$(git log -Sfoo bar --format=format:%H)
fatal: ambiguous argument 'bar': unknown revision of path not in the working tree.
具體是這樣的:-Sfoo bar。應該是-S"foo bar"或-S "foo bar"。因為要傳遞帶空格的引數,我們需要參考引數。但是,每次引數通過命令/函式層時,都會提取一層引號( '', )。""所以,我們需要嵌套參考。
所以在這一行:
declare -a searchContents=('foo' 'bar' ' foo ' 'foo bar')
更改'foo bar'為'"foo bar"'或"'foo bar'"或"\"foo bar\""。
這是 2 層嵌套引號的情況。層數越多,就越棘手。這是我曾經做過的 4 層參考的示例。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/421362.html
標籤:
上一篇:Golang使用標志執行函式
