我有一個非常基本的功能。
t() {
[[ -f ./terragrunt.hcl ]] && local exe=terragrunt
[[ ! -f ./terragrunt.hcl ]] && local exe=terraform
[[ ! $exe ]] && echo -e "\033[31;1m[ERROR]\033[0m Can't figure out what to run. Please run manually"
local cmd="$exe $@"
[[ $DEBUG ]] && echo -e "\033[34;1m[DEBUG]\033[0m executable is $exe.
Args are $@
Command to be run: $cmd"
$cmd
}
但是,當我像它一樣運行它t outputs
時t:9: command not found: terraform output
我可以運行terraform output
并獲得正確的輸出。
我也試過了eval
,return
都不管用。
uj5u.com熱心網友回復:
根本不要使用cmd
;沒有好的方法可以在單個字串中正確編碼有效的命令列。
t() {
[[ -f ./terragrunt.hcl ]] && local exe=terragrunt
[[ ! -f ./terragrunt.hcl ]] && local exe=terraform
[[ ! $exe ]] && echo -e "\033[31;1m[ERROR]\033[0m Can't figure out what to run. Please run manually"
[[ $DEBUG ]] && echo -e "\033[34;1m[DEBUG]\033[0m executable is $exe.
Args are $@
Command to be run: $exe $@"
"$exe" "$@"
}
構建由任意值產生的命令的準確字串表示$@
是非常重要的,幾乎不值得做。
uj5u.com熱心網友回復:
問題是你正在做:
local cmd="$exe $@"
$exe
這從and中構造了一個字串$@
,當您使用$cmd
它時,它將嘗試將該字串作為命令運行,包括空格,就好像您輸入了"terraform output"
(它將嘗試查找/bin/terraform output
)而不是terraform output
. 因此你的錯誤:
t:9: command not found: terraform output
在 zsh 中處理這個問題的最簡單方法是使用陣列:
local cmd=($exe $@)
$cmd
uj5u.com熱心網友回復:
分詞發生在 zsh 中的引數擴展之前。在您的情況下,您將不得不使用
${(z)cmd}
告訴 zsh 你想在展開之后再進行一輪分詞。但是,這會將內部的所有內容cmd
分詞。我想避免這種情況,創建cmd
一個陣列,其中命令本身是第一個元素,每個后續元素都是一個引數,并將其呼叫為
$cmd[@]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/503776.html
下一篇:迭代地將字串添加到bash陣列