【问题标题】:Checking if file exists before removing it in makefile在makefile中删除之前检查文件是否存在
【发布时间】:2016-02-10 01:42:03
【问题描述】:

我在 C++ 项目中有一个 makefile(编译器:C++11)。如何在使用 makefile 命令删除特定文件之前检查它是否存在?
代码如下:

bin: charstack.h error.h
        g++ -Wall -std=c++11 main.cpp charstack.cpp error.cpp -o bin

run:
        ./bin.exe

clean:
        rm bin.exe

# This statement removes auto generated backups on my system.
cl:
        rm charstack.h~ charstack.cpp~ main.cpp~ makefile~ error.h~ error.cpp~

我如何让 makefile 检查自动生成的 .~ 备份文件是否存在,然后再尝试在用户通过时删除它们

make cl

在命令行中?这里的目标是避免在运行“make cl”时将这些错误输出到终端:

rm: cannot remove `charstack.h~': No such file or directory
rm: cannot remove `charstack.cpp~': No such file or directory
rm: cannot remove `main.cpp~': No such file or directory
rm: cannot remove `error.h~': No such file or directory
rm: cannot remove `error.cpp~': No such file or directory
make: *** [cl] Error 1

【问题讨论】:

  • 之前的标题更好。现在它 (a) 无法描述,并且 (b) 命名错误的技术。

标签: makefile gnu-make


【解决方案1】:

老实说,这是一个 XY 问题,这既不是因为该项目是 C++ 项目,也不是因为它使用规范 C++11。

因此,问题的标题及其标签有点误导。

无论如何,您可以使用选项-f。来自rm的手册页:

忽略不存在的文件和参数,从不提示

所以,使用以下行就足够了:

 rm -f charstack.h~ charstack.cpp~ main.cpp~ makefile~ error.h~ error.cpp~

实际上,它不会检查那些文件是否存在,但如果它们不存在它也不会抱怨。

【讨论】:

  • 这确实是规范的做法。
  • 轻松修复。非常感谢!
  • 不客气。如果它解决了您的问题,请不要忘记接受回复,它将帮助新人和未来的搜索。
  • 您知道 Windows 8.0 Powershell 是否支持类似于 man 函数的功能吗?
  • 很遗憾没有,但我建议您搜索整个 SO 并最终打开一个新问题。 :-)
【解决方案2】:

即使这个问题已经得到解答,我还是附上了一个适用于两个文件 AND 目录的不同解决方案(因为 rm -rf DIRNAME 不再沉默)

只有当目录存在时,才能删除变量${OUTDIR} 中的目录。该示例很容易针对文件进行调整:

clean:
    if [ -d "${OUTDIR}" ]; then \
        rm -r ${OUTDIR}; \
    fi \

请注意,关键的观察是您必须编写通常的 bash if-then-esle,就好像它在单行上一样(即在换行符之前使用\,在每个命令之后使用;) .该示例可以很容易地适应不同的(非 bash)shell。

【讨论】:

    猜你喜欢
    • 2012-01-10
    • 2011-07-30
    • 1970-01-01
    • 1970-01-01
    • 2010-09-27
    • 2016-12-02
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    相关资源
    最近更新 更多