【问题标题】:Cannot tar array of files with spaces inside filename inside bash script无法在 bash 脚本内的文件名中包含空格的文件数组
【发布时间】:2019-03-18 17:53:12
【问题描述】:

我有 bash 脚本 my_tar.sh,它在 3 个文件上调用 tar czf output.tgz,文件名空间从数组传递:filefile 2file 3

#!/bin/bash

declare -a files_to_zip

files_to_zip+=(\'file\')
files_to_zip+=(\'file 2\')
files_to_zip+=(\'file 3\')

echo "tar czf output.tgz "${files_to_zip[*]}""
tar czf output.tgz "${files_to_zip[*]}" || echo "ERROR"

虽然存在三个文件,但当在脚本中运行tar 时,它会以错误结束。但是,当我在 bash 控制台中运行 echo 输出(与 my_tar.sh 的下一个命令相同)时,tar 运行正常:

$ ls
file  file 2  file 3  my_tar.sh
$ ./my_tar.sh
tar czf output.tgz 'file' 'file 2' 'file 3'
tar: 'file' 'file 2' 'file 3': Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors
ERROR
$ tar czf output.tgz 'file' 'file 2' 'file 3'
$ 

有什么想法吗?

【问题讨论】:

  • 看看declare -p files_to_zip
  • @Cyrus 哦,我明白了。这:@ and * 解释了我的困惑

标签: arrays bash tar quoting


【解决方案1】:

问题是,您将' 转义,从而将其添加到文件名中,而不是使用它来引用字符串:

files_to_zip+=(\'file 2\')

files_to_zip+=( 'file 2' )

此外,通常建议使用 @ 而不是星号 (*) 来引用所有数组元素,因为星号在引用时不会被解释(-> http://tldp.org/LDP/abs/html/arrays.html,示例 27-7) .

我还假设您的意图是在打印出数组元素时在字符串中加上引号。为此,您需要转义引号。

echo "tar czf output.tgz \"${files_to_zip[@]}\""

你的固定脚本看起来像

#!/bin/bash

declare -a files_to_zip

files_to_zip+=( 'file' )
files_to_zip+=( 'file 2' )
files_to_zip+=( 'file 3' )

echo "tar czf output.tgz \"${files_to_zip[@]}\""
tar czf output.tgz "${files_to_zip[@]}" || echo "ERROR"

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 2011-10-14
    • 2014-09-26
    • 2013-03-08
    • 1970-01-01
    • 2015-11-13
    • 2014-11-08
    • 1970-01-01
    • 2013-02-22
    相关资源
    最近更新 更多