Skip to the workspace
Pebellslearn by building
Your First Bash Script  ›  Lesson

Three Ways to Run a Script

Direct Execution 12 minA script can be executed directly or with the bash command, both of which run it in a separate child process, or sourced, which runs it inside your current shell.

shell bash / Three Ways to Run a Script

Explore each scene at your own pace.

01 · The rule

The rule

Three Ways to Run a Script

A script can be executed directly or with the bash command, both of which run it in a separate child process, or sourced, which runs it inside your current shell.

Compare launching a new shell, executing a script and sourcing it into the current shell.

You saved backup.sh, typed backup.sh, and got command not found. You tried ./backup.sh and got Permission denied. Then a friend's setup script "worked" but changed nothing in your terminal. All three puzzles have the same answer: how you run a script decides where it runs.

The rule

./ and bash run it in a child; source runs it here.

1. Direct execution. Give the file execute permission once, then run it by path:

chmod +x backup.sh
./backup.sh

This needs the shebang, because the system reads it to choose the interpreter. The ./ means "the file in this folder": your current folder is normally not on the PATH, so plain backup.sh is not found.

2. Running with bash. Hand the file to Bash yourself:

bash backup.sh

No execute permission is needed, and the shebang is just a comment now, since you already chose the interpreter.

3. Sourcing. Run the lines inside the shell you are typing in:

source project-env.sh    # or the short form:  . project-env.sh

Both 1 and 2 start a child process: a fresh Bash that runs the script and then exits. Anything it changes about itself (its current folder, its variables) disappears with it. Sourcing starts nothing new, so a cd or a variable set in the file stays in your terminal. That is exactly how ~/.bashrc is loaded.

# goto.sh contains one line:  cd /tmp
./goto.sh;       pwd    # still in your old folder
source goto.sh;  pwd    # now in /tmp
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.