Skip to main content
0 reactions

How to Run a Script in the Current Shell with source

Featured card for How to Run a Script in the Current Shell with source: a greet.sh file that sets NAME=Asha, an echo command that prints Hello, Asha, and the notes source greet.sh first and Its variables stay set.
How to Run a Script in the Current Shell with source

source runs the commands in a file inside the shell you’re typing in, so anything the file sets, such as a variable, is still set afterwards. Running the same file with zsh starts a separate shell, which forgets its variables when it ends.

Every command and output on this page is real, run in zsh on macOS.

Syntax

SyntaxBash
source <file>
  • source: zsh’s command for running a file’s commands in the current shell.
  • <file>: the path to the file, such as greet.sh in the current folder.

See source in the zsh manual’s Shell Builtin Commands (opens in a new tab).

The Example

A one-line file, greet.sh, that sets a variable named NAME.

Step 1: Write the File

greet.shBash
NAME=Asha

Step 2: Run It Without source

Run the file with zsh, then print a greeting that uses NAME:

TerminalBash
zsh greet.sh
echo "Hello, $NAME"
OutputPlain text
Hello, 

zsh greet.sh ran the file in a separate shell, so NAME was gone when it finished.

Step 3: Run It with source

TerminalBash
source greet.sh
echo "Hello, $NAME"
OutputPlain text
Hello, Asha

This time the file ran in your own shell, so NAME is still set.

Common Mistakes

MistakeWhat happensDo this instead
A wrong file name: source greeting.shzsh stops: source: no such file or directory: greeting.shCheck the file’s name and the folder you’re in

FAQ

Where will I see source?

When you activate a Python virtual environment: source .venv/bin/activate runs the environment’s activate script in your shell, so the environment stays on for the commands you type next.

Does a variable set with source last forever?

No. It lasts until you close that Terminal window or tab. A new window starts a new shell without it.

Conclusion

Use source when a file must change your own shell, for example to set variables. Running the file with zsh changes only a separate shell, which ends with the file.

Additional Resources

0 comments