无法理解这个 bash shell 参数扩展

pie*_*oni 3 bash quoting

对以下命令完全疯狂:

declare -a partition_files
readarray -d '' partition_files < <(find "$choosen_image_folder" -name "*sda${i}.gz*")

# this does not work
/bin/cat "${partition_files[*]}" | /bin/gunzip -f -c | ntfsclone -r -O "/dev/sda$i" -
# this does work
/bin/cat ${partition_files[*]} | /bin/gunzip -f -c | ntfsclone -r -O "/dev/sda$i" -
# this does not work
/usr/sbin/partimage restore -b "/dev/sda$i" "${partition_files[*]}"
# this does work
/usr/sbin/partimage restore -b "/dev/sda$i" ${partition_files[*]}
Run Code Online (Sandbox Code Playgroud)

为什么在这种情况下删除引用有效而引用无效?

ilk*_*chu 6

"${partition_files[*]}"使用第一个字符作为连接符,将所有数组元素连接到一个shell 字IFS。因此,如果数组是a=("foo bar" asdf),并且IFS具有默认值,您将获得与 相同的值"foo bar asdf"

您想要的是"${partition_files[@]}",它使每个元素成为一个不同的词,因此与"foo bar" "asdf".

"$@""$*"and之间的区别相同,一般来说,除非您知道自己在做一些特别的事情,否则您总是想要"$@", or "${array[@]}"(带有 at 符号和引号)。

如果${array[*]}不使用引号,则会分别获取所有元素,然后再次拆分每个单词。(如果IFS不是空串,基本上就是把所有元素串联起来,然后组合分词。)

参见例如https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html