【问题标题】:How to store filenames with spaces in a variable and pass them to commands in a bash script? [duplicate]如何在变量中存储带空格的文件名并将它们传递给 bash 脚本中的命令? [复制]
【发布时间】:2020-11-13 08:08:39
【问题描述】:

我在 bash 脚本中处理带有空格的文件名时遇到问题。

使用:

cat hello\ message\ \(1\).txt

成功打印文件内容。

使用:

file=hello\ message\ \(1\).txt
cat $file

返回:

cat: hello: No such file or directory
cat: message: No such file or directory
cat: '(1).txt': No such file or directory

如何在变量中存储带空格的文件名并将它们传递给命令?

【问题讨论】:

  • 使用引号。 cat "$file"

标签: bash double-quotes


【解决方案1】:

变量有正确的值,它是失败的扩展。经验法则:总是引用变量扩展。

cat "$file"

未加引号的变量扩展受glob expansion and word splitting 约束。把它想象成有一个隐藏的split_glob() 函数在你省略引号时被调用。 *? 和其他 glob 被扩展,空格被解释为单词分隔符。

【讨论】:

    猜你喜欢
    • 2016-04-21
    • 2012-10-21
    • 1970-01-01
    • 1970-01-01
    • 2020-11-02
    • 2021-03-20
    • 1970-01-01
    • 2014-05-09
    • 2019-01-31
    相关资源
    最近更新 更多