bash - 压缩多个文件,从变量中获取参数,其中一个在名称中有空格[重复]

问题描述 投票:1回答:1

这个问题在这里已有答案:

我想拉上file.txtfile with spaces.txt。我需要将它们保存在一个变量中。我可以像这样连接这些字符串:

files="$files \"$newfilename\""

然后我将所有文件名放在一个变量中,用空格分隔,每个变量都用引号括起来。 “file.txt”“带有spaces.txt的文件”

所以我现在需要拉链。但是,如果我这样做:

tar czf output $files

然后bash会产生:

tar czf output '"file.txt."' '"file' with 'spaces.txt"'

如果我做

tar czf output "$files"

那么bash会做:

tar czf output '"file.txt." "file with spaces.txt"'

在第一种情况下,bash在每个单词之后和之前插入一个撇号,在第二种情况下,tar将两个文件作为一个名称。如果我在tar czf "file.txt" "file with spaces.txt"变量中有这个字符串,我该怎么做才能生成$files

bash variables tar quotation-marks
1个回答
2
投票

使用变量存储独立的多个单词条目。使用数组并正确引用文件名,以保留带空格的名称

declare -a files=()
files=("file.txt")
files+=("file with spaces.txt")

+=()用于将元素附加到现有数组。现在扩展数组是将列表传递给zip所需的内容

tar czf output "${files[@]}"

关于OP关于做files=()declare -a files=()之间的背景的问题。它们可能是相同的,并且在初始化索引数组的相同上下文中工作。但是当你在没有declare -a files部分的情况下做()时会发生明显的差异。因为declare -a没有重新初始化已定义的数组,但=()清空了它。请参阅下面的示例

prompt> files=()
prompt> files+=(a "new word")
prompt> files+=("another word")
prompt> echo "${files[@]}"
a new word another word

现在做files=()会完全清空现有的数组,

prompt> files=()                   # array completely emptied now
prompt> echo "${files[@]}"
                                   # empty result

但与之前和做的内容相同

prompt> echo "${files[@]}"
a new word another word
prompt> declare -a files           # an existing array is not emptied
prompt> echo "${files[@]}"
a new word another word
© www.soinside.com 2019 - 2024. All rights reserved.