brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: source runs a file in your current shell, ./script in a new one

Shell
~/tips/tip-shell-source-vs-run

source s.sh; echo "$PWD $X" # /tmp 1

Know why cd and variables from a script vanish, and when source keeps them.

A script that sets variables or changes folder seems to do nothing when you run it. That is because ./script.sh starts a new shell, and everything it changes dies with it.

Compare the two with a file that changes folder and sets a variable:

echo 'cd /tmp; X=1' > s.sh
bash s.sh;   echo "$PWD $X"   # old folder, X empty
source s.sh; echo "$PWD $X"   # /tmp 1

source (or its short form .) reads the file and runs its lines in your current shell, as if you typed them. Its cd, variables, functions and aliases stay after it finishes.

That is how ~/.bashrc, Python’s venv/bin/activate and most .env loaders work. I’d use it for small files with settings that several scripts share.

The flip side is that a sourced file can also break your shell. An exit inside it closes your terminal, and a set -e stays active and closes the shell at the next failing command. So only source files you trust and that were written to be sourced. In plain sh, use . because source is a bash word, and give a path with a slash, like . ./s.sh, or it searches PATH first.

Further reading: Bash manual: Bourne Shell Builtins (source)

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link