【问题标题】:How to detect whether a file with spaces in its name exists?如何检测名称中带有空格的文件是否存在?
【发布时间】:2013-07-20 11:54:04
【问题描述】:

我正在尝试检测是否存在名为 semester1 (2013).csv 的文件。

到目前为止,我有以下内容:

file="results/semester1\ (2013).csv"
if [ -f $file ]; then
  echo 'File exists.'
fi

这会产生以下错误:

binary operator expected

我没有正确逃避什么?

【问题讨论】:

    标签: string bash file-io escaping


    【解决方案1】:

    你转义太多,但引用不够:

    file="results/semester1 (2013).csv"
    if [ -f "$file" ]; then
      echo 'File exists.'
    fi
    

    如果您不引用 "$file",它会在测试中扩展为两个“单词”,并且会失败。加上引号,整个测试就通过了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-10
      • 1970-01-01
      • 2014-04-19
      • 2012-02-25
      相关资源
      最近更新 更多