Three Ways to Run a Script
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
./andbashrun it in a child;sourceruns it here.
1. Direct execution. Give the file execute permission once, then run it by path:
chmod +x backup.sh
./backup.shThis 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.shNo 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.shBoth 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 /tmpThe shortcut
Ask one question: should this file change my shell? Tools like backup.sh just do a job, so execute them. Files that set up your environment (variables, folder, aliases) must be sourced. Then read error messages by their first word: command not found means a PATH problem (add ./), Permission denied means a missing execute bit (chmod +x, or use bash).
The file
project-env.shrunscd ~/projectandexport PROJECT=notes.
One warning: exit inside a sourced file exits your shell, which can close the terminal window. Keep exit in scripts you execute, not in files you source.
Drills
Answer fast — trust the rule.
backup.sh is in your current folder, but typing backup.sh says command not found. Why?
./backup.sh says Permission denied. Which fix lets you keep running it that way?
setvars.sh contains export PROJECT=notes. After bash setvars.sh, what does echo "$PROJECT" print in your terminal?
Which of these runs a script that has no execute permission?
goto.sh contains cd /tmp. You run . ./goto.sh and then pwd. What prints?
Remember
./andbashrun a script in a child;source(or.) runs it here.- Ask "should it change my shell?" Yes means source; no means execute.
- command not found means add
./; Permission denied meanschmod +x. Neverexitin a sourced file.
