Terminal closes when I source my script (run with dot at the start)
Replace all exit
with return
.return
inside a sourced script will even work with exit codes:
$ . <(echo "echo before; return 0; echo after")
before
$ echo $?
0
$ . <(echo "echo before; return 7; echo after")
before
$ echo $?
7
bash: exit from sourced script
It seems there could be 2 parts to this. The first is to know when you're executing in a source
d script instead of an executed one. That can be found in this answer, and for bash they suggest:
[[ "$0" != "$BASH_SOURCE" ]] && sourced=1 || sourced=0
to tell whether or not you are being sourced.
If you are being sourced, you'd want to use return
instead of exit
.
You could store that function in a variable with something like
if [[ $sourced -eq 1 ]]; then
ret=return
else
ret=exit
fi
and then when you want to use the appropriate one you'd just use
$ret 1
Shell script closes iterm2 on exit
Using:
. myscript.sh
You are actually running the script in the existing shell or "sourcing" the script. With exit at the end of the script, this means that the terminal session will also exit
Alternatively:
./myscript.sh
or
bash myscript.sh
Will run the script in a separate bash shell and stop the terminal session from exiting.
unix command line execute with . (dot) vs. without
. name
sources the file called name
into the current shell. So if a file contains this
A=hello
Then if you sources that, afterwards you can refer to a variable called A
which will contain hello. But if you execute the file (given proper execution rights and #!/interpreter
line), then such things won't work, since the variable and other things that script sets will only affects its subshell it is run in.
Sourcing a binary file will not make any sense: Shell wouldn't know how to interpret the binary stuff (remember it inserts the things appearing in that file into the current shell - much like the good old #include <file>
mechanism in C). Example:
head -c 10 /dev/urandom > foo.sh; . foo.sh # don't do this at home!
bash: �ǻD$�/�: file or directory not found
Executing a binary file, however, does make a lot of sense, of course. So normally you want to just name the file you want to execute, and in special cases, like the A=hello
case above, you want to source a file.
How do I get the directory where a Bash script is located from within the script itself?
#!/usr/bin/env bash
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
is a useful one-liner which will give you the full directory name of the script no matter where it is being called from.
It will work as long as the last component of the path used to find the script is not a symlink (directory links are OK). If you also want to resolve any links to the script itself, you need a multi-line solution:
#!/usr/bin/env bash
SOURCE=${BASH_SOURCE[0]}
while [ -L "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )
SOURCE=$(readlink "$SOURCE")
[[ $SOURCE != /* ]] && SOURCE=$DIR/$SOURCE # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )
This last one will work with any combination of aliases, source
, bash -c
, symlinks, etc.
Beware: if you cd
to a different directory before running this snippet, the result may be incorrect!
Also, watch out for $CDPATH
gotchas, and stderr output side effects if the user has smartly overridden cd to redirect output to stderr instead (including escape sequences, such as when calling update_terminal_cwd >&2
on Mac). Adding >/dev/null 2>&1
at the end of your cd
command will take care of both possibilities.
To understand how it works, try running this more verbose form:
#!/usr/bin/env bash
SOURCE=${BASH_SOURCE[0]}
while [ -L "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
TARGET=$(readlink "$SOURCE")
if [[ $TARGET == /* ]]; then
echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'"
SOURCE=$TARGET
else
DIR=$( dirname "$SOURCE" )
echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')"
SOURCE=$DIR/$TARGET # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
fi
done
echo "SOURCE is '$SOURCE'"
RDIR=$( dirname "$SOURCE" )
DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )
if [ "$DIR" != "$RDIR" ]; then
echo "DIR '$RDIR' resolves to '$DIR'"
fi
echo "DIR is '$DIR'"
And it will print something like:
SOURCE './scriptdir.sh' is a relative symlink to 'sym2/scriptdir.sh' (relative to '.')
SOURCE is './sym2/scriptdir.sh'
DIR './sym2' resolves to '/home/ubuntu/dotfiles/fo fo/real/real1/real2'
DIR is '/home/ubuntu/dotfiles/fo fo/real/real1/real2'
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
.
Related Topics
How to Run Multiple Programs in a Sequence
Bash -C Variable Does Not Get Assigned
Print Differences of File1 to File2 Without Deleting Anything from File2
Phusion Passenger Nginx Module Installer V3.0.17 Issue on Debian 6.0.5 Amd64 Due to Broken Package
Update Specific Field in Text File in Specific Line
Dotnetcore: Cross Platform Version of Getinvalidfilenamechars
Replace Line with Space and Backslash with a String Containing Spaces
One-Liner: Print All Lines Except the Last 3
Linux Perf Record: Difference Between Count (-C) and Frequency (-F) Options
How to Merge Two Rows in a Same Row from a Text File in Linux Shell Script
A Way to Prevent Bash from Parsing Command Line W/Out Using Escape Symbols
When Installing Rust Toolchain in Docker, Bash 'Source' Command Doesn't Work
How to Start/Restart/Stop Apache Server on Linux as Non-Root User
Shell Script to Delete Files When Disk Is Full
Opening New Gnome-Terminal (V3.28+) with Multiple Tabs and Different Commands