bash 有条件地退出/中止 shell 脚本执行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7662972/
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-18 00:55:26  来源:igfitidea点击:

exit / abort shell script execution conditionally

bashexit

提问by Tom Auger

I'm writing a bash script that leverages getopt to process a number of options provided after the script name.

我正在编写一个 bash 脚本,它利用 getopt 来处理脚本名称后提供的许多选项。

I'm accessing my shell through puTTy.

我正在通过 PuTTy 访问我的 shell。

I invoke the script with . scriptname.sh -o --options (is there a better way to execute a bash script?)

我用 . scriptname.sh -o --options(有没有更好的方法来执行 bash 脚本?)

I'd like to be able to abort / halt the script, but whenever I use exitit not only exits the script, it also closes the terminal/puTTy window.

我希望能够中止/停止脚本,但是每当我使用exit它时,它不仅会退出脚本,还会关闭终端/puTTy 窗口。

...which kinda defeats the purpose because what I'm trying to do is set up some kind of --help text output that displays the text but doesn't execute the rest of the script.

...这有点违背了目的,因为我想做的是设置某种 --help 文本输出,显示文本但不执行脚本的其余部分。

What's the deal with exitand what should I use to halt/abort the script without closing any parent console window?

这是exit怎么回事,我应该用什么来停止/中止脚本而不关闭任何父控制台窗口?

回答by sorpigal

Using exitis correct, you're just not executing your script correctly.

使用exit是正确的,您只是没有正确执行脚本。

Using .is the same as using the sourcecommand (help sourcefor usage) and is not a good idea if you really wanted to execute the script.

使用.与使用source命令(help source用于用法)相同,如果您真的想执行脚本,这不是一个好主意。

Instead chmod a+x scriptname.shand then use ./scriptname.shto invoke it.

相反chmod a+x scriptname.sh,然后使用./scriptname.sh它来调用它。

The difference is that sourcetreats the script as if it had been typed in by you; it runs in the same bashsession that you're running interactively. This means that any variables it changes remain changed after it finishes. It also means that if you tell the script to exit, it will correctly terminate your current bash session.

不同之处在于source将脚本视为由您输入;它在bash您交互式运行的同一会话中运行。这意味着它更改的任何变量在完成后仍保持更改状态。这也意味着如果您告诉脚本exit,它将正确终止您当前的 bash 会话。