[英]Why is the same command different when stored to variable vs output to stdout?
我正在使用以下輸出:
OUTPUT="VAL1 VAL2 VAL3 VAL4" #(two spaces between each VAL)
我正在嘗試將輸出存儲在變量SAMPLE中,以替換腳本中運行的雙引號作為逗號:
SAMPLE=$(echo $OUTPUT | sed 's/\ \ /\,/g'); echo $SAMPLE
返回VAL1 VAL2 VAL3 VAL4
(每個val之間有一個空格)
但是,如果我在不將其存儲到變量的情況下運行它,則會得到不同的輸出
echo $OUTPUT | sed 's/\\ \\ /\\,/g')
echo $OUTPUT | sed 's/\\ \\ /\\,/g')
根據需要返回VAL1,VAL2,VAL3,VAL4
通常,您應該始終在bash中引用變量以保留格式(除非您出於某些原因不使用引號,例如,想要擴展,想要在[[]]
內使用echo $variable
限制某些空間,例如hack [[]]
(可選),等等)
$ echo $OUTPUT
VAL1 VAL2 VAL3 VAL4"
$ echo "$OUTPUT"
VAL1 VAL2 VAL3 VAL4
$ SAMPLE=$(echo "$OUTPUT" | sed 's/\ \ /\,/g'); echo "$SAMPLE"
VAL1,VAL2,VAL3,VAL4
echo $OUTPUT | sed 's/\\ \\ /\\,/g'
echo $OUTPUT | sed 's/\\ \\ /\\,/g'
不會導致逗號分隔的列表(不帶$OUTPUT
),除非您有一些奇怪的echo
/ shell
。
另外,在bash中使用caps變量名稱可能不是最佳約定,因為它們僅用於內部變量(例如$PWD
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.