在 bash 中,我逐行決議檔案并提取第一個和第二個欄位,如下所示:
$ cat myfile
a1 1
a2 2
a3 3
a4
$ while read -r first second; do echo first is $first second is $second; done < myfile
first is a1 second is 1
first is a2 second is 2
first is a3 second is 3
first is a4 second is
現在,我需要將上述命令包含在 中bash -c,因為它將通過kubectl exec. 它沒有按預期作業,只評估它在最后一行決議的內容:
$ bash -c "while read -r first second; do echo first is $first second is $second; done < myfile"
first is a4 second is
first is a4 second is
first is a4 second is
first is a4 second is
這里缺少什么?
謝謝!
uj5u.com熱心網友回復:
您的引數在父 shell 中擴展,更改您的引號或轉義引數擴展:
$ bash -c 'while read -r first second; do echo first is $first second is $second; done < myfile'
或者
$ bash -c "while read -r first second; do echo first is \$first second is \$second; done < myfile"
請注意,您幾乎應該總是用雙引號將引數擴展包起來:
echo "$a"
代替
echo $a
避免分詞和路徑名擴展。
考慮以下示例,在 POSIX shell 中:
a="hello *"; echo $a;
對比
a="hello *"; echo "$a";
所以這會讓你的腳本最終看起來像:
$ bash -c 'while read -r first second; do echo first is "$first" second is "$second"; done < myfile'
uj5u.com熱心網友回復:
如果您不想處理復雜的 shell 雙引號,首先定義一個函式,您可以在其中手動鍵入代碼,shellcheck 也可以幫助您鍵入正確的代碼:
f() {
while IFS=' ' read -r first second; do
echo "first is $first second is $second";
done
}
然后做:
printf "%q\n" "$(declare -f f); f"
$'f () \n{ \n while IFS=\' \' read -r first second; do\n echo "first is $first second is $second";\n done\n}; f'
declare以可重用的形式列印函式定義,然后我們f呼叫函式。然后你可以復制輸出并在 shell 中重新使用它:
bash -c $'f () \n{ \n while IFS=\' \' read -r first second; do\n echo "first is $first second is $second";\n done\n}; f'
這$'...'是特定于 Bash C 參考樣式的,因此請使用與printf %q需要時不同的參考函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/350660.html
