延伸到這樣一個問題: Bash : Adding extra single quotes to strings with spaces擊數組變量擴展內部期望命令
存儲命令的參數作爲一個bash陣列
touch "some file.txt"
file="some file.txt"
# Create an array with two elements; the second element contains whitespace
args=(-name "$file")
# Expand the array to two separate words; the second word contains whitespace.
find . "${args[@]}"
然後,在陣列中存儲整個命令後
finder=(find . "${args[@]}")
在bash中我可以運行命令如下:
"${finder[@]}"
./some file.txt
但是,當我嘗試使用想到,我得到錯誤
expect -c "spawn \"${finder[@]}\""
missing "
while executing
"spawn ""
couldn't read file ".": illegal operation on a directory
爲什麼bash的變量擴展不發生在這裏?
用用戶的原始參數試試這個;你會得到'spawn'find。-name some file.txt「'。 – chepner
@chepner補充說明。 – muru
提供一個關於'bash'數組的問題的答案,僅當數組的元素不包含空格時才起作用。數組存在的全部原因是處理包含空白的元素。 – chepner