現在我使用這個 bash 命令:
$ yarn b types && yarn w types && yarn g types && yarn s types
是否可以在 bash 中生成這樣的命令?(偽代碼):
$ exec ['b', 'w', 'g', 's'].map(input => `yarn ${input} types`).join(" && ")
如果可能,這里將使用哪種語法?
我將在我的 package.json 檔案(節點)中使用這個腳本。yarn workspaces foreach 不適合這里,因為它的輸出很差
uj5u.com熱心網友回復:
良好做法替代方案:使用回圈
代碼生成具有嚴重的安全隱患,通常僅供專家使用。此外,在目前的情況下,您不需要它:一個回圈就足夠了。
buildAll() {
for input; do
yarn "$input" type || return
done
}
buildAll b w g s
...具有相同的行為,如果 、 或 中的任何一個失敗,則以非零狀態提前yarn b type退出,yarn w type如果所有四個都成功,則以成功/零狀態退出。yarn g typeyarn s type
作為單線,這將是:
buildAll() { for i; do yarn "$i" type || return; done; }; buildAll b w g s
如果您的專案在陣列中,這不會有任何實質性的變化;如果你有:
types=( b w g s )
...然后,只需替換buildAll b w g s為buildAll "${types[@]}"
您的要求:執行代碼生成
在執行您在自己的代碼中看到的任何操作之前,請查看BashFAQ #48關于與eval.
${var@Q}擴展需要 bash 5.0 或更高版本;對于舊版本的 bash,printf %q是轉義變數內容以安全決議為代碼的替代方法。請注意,這并不比上述替代方案更短或更易讀,并且仍然涉及回圈!
:用作同義詞true;它讓我們使回圈的所有迭代都相同,無條件地添加 a &&。
types=( b w g s )
statement=':'
for type in "${types[@]}"; do
statement =" && yarn ${type@Q} types"
done
eval "$statement"
支持舊版本 bash 的版本是:
types=( b w g s )
statement=':'
for type in "${types[@]}"; do
printf -v type_q '%q' "$type"
statement =" && yarn $type_q types"
done
eval "$statement"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/493725.html
