检查文件是否存在并在 Bash 中继续否则退出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9146136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:37:39  来源:igfitidea点击:

Check if file exists and continue else exit in Bash

bashif-statementcontinue

提问by user1190083

I have a script that is one script in a chain of others that sends an email.

我有一个脚本,它是发送电子邮件的一系列其他脚本中的一个。

At the start of the script I want to check if a file exists and continue only if it exists, otherwise just quit.

在脚本开始时,我想检查一个文件是否存在,只有在它存在时才继续,否则就退出。

Here is the start of my script:

这是我的脚本的开始:

if [ ! -f /scripts/alert ];
then
    echo "File not found!" && exit 0
else
        continue
fi

However I keep getting a message saying:

但是我不断收到一条消息说:

line 10: continue: only meaningful in a `for', `while', or `until' loop

Any pointers?

任何指针?

回答by Kerrek SB

Change it to this:

改成这样:

{
if [ ! -f /scripts/alert ]; then
    echo "File not found!"
    exit 0
fi
}

A conditional isn't a loop, and there's no place you need to jump to. Execution simply continues after the conditional anyway.

条件不是循环,而且您无需跳转到任何地方。无论如何,执行只是在条件之后继续。

(I also removed the needless &&. Not that it should happen, but just in case the echofails there's no reason not to exit.)

(我也删除了不必要的&&。并不是说它应该发生,但万一echo失败,没有理由不退出。)

回答by Pluckerpluck

Your problem is with the continueline which is normally used to skip to the next iteration of a foror whileloop.

您的问题在于continue通常用于跳到fororwhile循环的下一次迭代的行。

Therefore just removing the elsepart of your script should allow it to work.

因此,只需删除else脚本的一部分即可使其工作。

回答by Kevin

Yes. Drop the else continue. It's entirely unneeded.

是的。放下else continue. 这是完全不需要的。