Exit Bash Mode

Any way to exit bash script, but not quitting the terminal

The "problem" really is that you're sourcing and not executing the script. When you source a file, its contents will be executed in the current shell, instead of spawning a subshell. So everything, including exit, will affect the current shell.

Instead of using exit, you will want to use return.

Exit Bash Mode?

Bash is a command line interpreter. It is one way to run commands on a linux system.

Are you saying that it isn't allowing you to run the commands you enter? What error or response is it giving when you run a command using bash?

In a Bash script, how can I exit the entire script if a certain condition occurs?

Try this statement:

exit 1

Replace 1 with appropriate error codes. See also Exit Codes With Special Meanings.

Automatic exit from Bash shell script on error

Use the set -e builtin:

#!/bin/bash
set -e
# Any subsequent(*) commands which fail will cause the shell script to exit immediately

Alternatively, you can pass -e on the command line:

bash -e my_script.sh

You can also disable this behavior with set +e.

You may also want to employ all or some of the the -e -u -x and -o pipefail options like so:

set -euxo pipefail

-e exits on error, -u errors on undefined variables, and -o (for option) pipefail exits on command pipe failures. Some gotchas and workarounds are documented well here.

(*) Note:

The shell does not exit if the command that fails is part of the
command list immediately following a while or until keyword,
part of the test following the if or elif reserved words, part
of any command executed in a && or || list except the command
following the final && or ||, any command in a pipeline but
the last, or if the command's return value is being inverted with
!

(from man bash)

Exit out of the bash script from mongo shell if a condition passes

You can make the script exit when mongo returns success:

mongo ${ssl_mode} --quiet <<EOF && exit
{
if(array.member!== 1) {
print("Successful Validation.");
quit(0); // exit mongo shell and exit bash script
} else {
//some code
quit(1); // exit mongo shell but continue bash script
}
EOF

How to safely exit early from a bash script?

The most common solution to bail out of a script without causing the parent shell to terminate is to try return first. If it fails then exit.

Your code will look like this:

#! /usr/bin/bash
# f.sh

func()
{
return 42
}

func
retVal=$?
if [ "${retVal}" -ne 0 ]; then
return ${retVal} 2>/dev/null # this will attempt to return
exit "${retVal}" # this will get executed if the above failed.
fi

echo "don't wanna reach here"

You can also use return ${retVal} 2>/dev/null || exit "${retVal}".

Hope this helps.



Related Topics



Leave a reply



Submit