2016-03-08 31 views
2

延伸到這樣一個問題: 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的變量擴展不發生在這裏?

回答

5

expect -c COMMAND要求COMMAND是一個參數。它不接受多字參數,這是"${finder[@]}"擴展到的。

如果你想處理空白完美無損,它會很棘手。 printf %q可能有用。

0

${finder[@]}在雙引號擴展到單獨的詞:

$ printf "%s\n" expect -c "spawn \"${finder[@]}\"" 
expect 
-c 
spawn "a 
b 
c" 

所以,expect沒有得到完整的命令作爲一個參數。可以使用*

$ printf "%s\n" expect -c "spawn \"${finder[*]}\"" 
expect 
-c 
spawn "a b c" 

${finder[*]}擴展陣列元件成單個字由IFS的第一個字符,這是默認的空間分離。但是,*所添加的空格與原始元素中的空格之間沒有區別,因此,您無法可靠地使用它。

+0

用用戶的原始參數試試這個;你會得到'spawn'find。-name some file.txt「'。 – chepner

+0

@chepner補充說明。 – muru

+1

提供一個關於'bash'數組的問題的答案,僅當數組的元素不包含空格時才起作用。數組存在的全部原因是處理包含空白的元素。 – chepner