簡體   English   中英

期望命令中的Bash數組變量擴展

[英]Bash array variable expansion inside expect command

此問題的擴展: Bash:在帶空格的字符串中添加額外的單引號

將命令的參數存儲為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時,出現錯誤

expect -c "spawn \"${finder[@]}\""
missing "
   while executing
"spawn ""
couldn't read file ".": illegal operation on a directory

為什么這里不進行bash變量擴展?

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

如果您想完美地處理空白而又不打擾,那將非常棘手。 printf %q可能有用。

雙引號${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的第一個字符分隔,默認情況下為空格。 但是, *添加的空格與原始元素中的空格之間沒有區別,因此,您不能可靠地使用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM