1

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

I'm accessing my shell through puTTy.

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

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

...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.

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

4
  • 1
    Yes, there's a better way to execute a script. In fact, using . is the same as using the source command (help source for usage) and is not a good idea if you really wanted to execute the script. Instead chmod a+x scriptname.sh and then use ./scriptname.sh to invoke.
    – sorpigal
    Commented Oct 5, 2011 at 14:35
  • And do not forget about shebang. Commented Oct 5, 2011 at 14:38
  • @maksenov: in fact it will work anyway, but you're right that a bang line is a good idea.
    – sorpigal
    Commented Oct 5, 2011 at 14:39
  • Nice! @Sorpigal. I'm just picking this stuff up in bits and pieces.
    – Tom Auger
    Commented Oct 5, 2011 at 14:44

1 Answer 1

8

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

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

Instead chmod a+x scriptname.sh and then use ./scriptname.sh to invoke it.

The difference is that source treats the script as if it had been typed in by you; it runs in the same bash session 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.

1
  • Brilliant. That makes perfect sense. Thanks for the super-quick response! (So fast in fact that I must wait 2 minutes to accept the answer...)
    – Tom Auger
    Commented Oct 5, 2011 at 14:45

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.