2

bash scripting noob here. I've found this article: https://www.shellhacks.com/print-usage-exit-if-arguments-not-provided/ that suggests putting
[ $# -eq 0 ] && { echo "Usage: $0 argument"; exit 1; }

at the top of a script to ensure arguments are passed. Seems sensible.

However, when I do that and test that that line does indeed work (by running the script without supplying any arguments: . myscript.sh) then the script does indeed exit but so does the bash session that I was calling the script from. This is very irritating.

Clearly I'm doing something wrong but I don't know what. Can anyone put me straight?

2
  • It's not clear what exactly you are doing. I guess that you run that line in your shell which was started as part of the session, and when it hits exit 1 that shell is closed. Commented Mar 9, 2018 at 14:30
  • Yes I think you're right, is there a way to prevent that from happening? Commented Mar 9, 2018 at 14:31

2 Answers 2

4

. myscript.sh is a synonym for source myscript.sh, which runs the script in the current shell (rather than as a separate process). So exit terminates your current shell. (return, on the other hand, wouldn't; it has special behaviour for sourced scripts.)

Use ./myscript.sh to run it "the normal way" instead. If that gives you a permission error, make it executable first, using chmod a+x myscript.sh. To inform the kernel that your script should be run with bash (rather than /bin/sh), add the following as the very first line in the script:

#!/usr/bin/env bash

You can also use bash myscript.sh if you can't make it executable, but this is slightly more error-prone (somebody might do sh myscript.sh instead).

Sign up to request clarification or add additional context in comments.

3 Comments

Perfect. Thanks @Thomas.
Well, the other obvious alternative is bash myscript.sh, which doesn't require executable bit or hashbang line.
Note that if your script does need to be executed with source, you can use return instead of exit.
1

Question seems not clear if you're sourcing script source script_name or . script_name it's interpreted in current bash process, if you're running a function it's the same it's running in same process, otherwise, calling a script, caller bash forks a new bash process and waits until it terminates (so running exit doesn't exit caller process), but when running exit builtin in in current bash it exits current process.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.