让“make clean”在执行前要求确认

37

有没有办法让make clean命令需要用户确认?我不小心执行了它,现在又要等待6个小时才能重新构建。

Makefile是由cmake创建的。

期望的工作流程:

> make clean
> [make] Are you sure you want to remove all the built files? [Y/N]
> N
> [make] Target 'make clean' not executed.

> make clean
> [make] Are you sure you want to remove all the built files? [Y/N]
> Y
> [make] Target 'make clean' executed.

CMake没有针对make clean的“提示”选项。我也不知道如何为clean目标附加其他操作。(影响make clean行为的唯一方法是将文件添加到ADDITIONAL_MAKE_CLEAN_FILES)。您可以创建另一个目标(比如make remove),在其中调用某种“提示”,然后再执行make clean - Tsyvarev
3个回答

61

我不熟悉cmake,但对于GNU make而言,一个可能的黑科技是:

clean: check_clean

check_clean:
    @echo -n "Are you sure? [y/N] " && read ans && [ $${ans:-N} = y ]

.PHONY: clean check_clean
如果check_clean失败(用户没有输入y),那么make将在执行清理之前退出并出现错误。

4
小小的改进: @echo -n "你确定吗?[y/N] " && read ans && [ $${ans:-N} == y ] - adrianlzt
4
我正在使用这个命令:@( read -p "你确定吗?!?[y/N]: " sure && case "$$sure" in [yY]) true;; *) false;; esac ) - spky
2
@HardcoreHenry:你确定是 [ $${ans:-N} == y ] 而不是 [ $${ans:-N} = y ] 吗?当我使用你的命令时,我的 Makefile 在输入任何内容时都会失败,但当我改为单个等号字符时,它就可以正常工作了。 - Be Chiller Too
2
两者对我来说都可以,但我刚查了一下,似乎“==”不符合Posix标准,因此在某些shell上可能无法使用。我会更新答案,使用单个“=”。谢谢。 - HardcoreHenry
1
为什么在 macOS 终端中输入 Are you sure? [y/N] 之前会显示 -n,而在 Linux 终端中却没有这种情况呢? - dragonfly02
显示剩余4条评论

2

Makefile:

clean:
    @read -p "Are you sure? [y/N] " ans && ans=$${ans:-N} ; \
    if [ $${ans} = y ] || [ $${ans} = Y ]; then \
        printf $(_SUCCESS) "YES" ; \
    else \
        printf $(_DANGER) "NO" ; \
    fi
    @echo 'Next steps...'



_SUCCESS := "\033[32m[%s]\033[0m %s\n" # Green text for "printf"
_DANGER := "\033[31m[%s]\033[0m %s\n" # Red text for "printf"

如果下一条语句不需要执行,我们可以使用“exit 1”来报错。 - Ashwin

1
我使用这个:
clean:
    @echo -n "Are you sure? [Y/n] " && read ans && [ $${ans:-Y} != Y ] && echo "Aborted" && exit 1
    ... Rest of code here

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接