0

I see that exit 1 in a shell script results in the 'Process complete' message, causing the shell to become unresponsive. Is there a way to use the exit command and return to a prompt? I don't want to have to open a new session, but I don't see another way.

Edit: I use . but I get the same result with source as well

2
  • Is this "exit 1 in a shell script" in a script you source? (with source or .). Aug 29, 2019 at 22:40
  • When you run a script with . or source, it runs in the current shell. In your case, that means it's running in your interactive shell. When it exits, it exits your interactive shell. You need to either run it normally (as a subprocess) (note that running it with ./scriptname instead of . scriptname will do this, provided it's executable and has a proper shebang), or have it use return instead of exit. Aug 30, 2019 at 1:15

1 Answer 1

1

Please see What does source do?

source is a bash shell built-in command that executes the content of the file passed as argument, in the current shell. It has a synonym in . (period).

exit in a sourced script makes the current shell exit, as if you typed exit. A scripts that is meant to be sourced should never exit its main shell (i.e. not a subshell) because its main shell is the shell you source the script from. Unless you know what you're doing and exit in a sourced script is really what you want.

You can return from a sourced script. If you need to source the script then return 1 may be the right thing instead of exit 1.

A script that is not meant to be sourced should not be sourced. If it invokes exit in its main shell then it's most likely meant to be executed. Another useful link: What is the difference between sourcing (. or source) and executing a file in bash?

So how to execute?

A command bash scriptname will run a separate bash process that will parse scriptname and execute its lines. If there is exit then it will exit the separate bash, not your current shell.

To be able to execute a script directly (like ./scriptname instead of bash scriptname) you need a proper shebang as the first line of the script, e.g.:

#!/bin/bash

and the file needs to be executable (chmod +x scriptname) and the filesystem holding the file must not be mounted with noexec option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.