Interview Prep/Shell Scripting/Shells, scripts and execution

What is the difference between `./script.sh`, `bash script.sh` and `source script.sh`?

BeginnerConceptShells, scripts and execution
Answer
  • ./script.sh needs the execute bit, honours the shebang and runs in a new process.
  • bash script.sh runs a new Bash process explicitly; the shebang and execute bit are ignored.
  • source script.sh (or . script.sh) runs the file inside the current shell: its variables, cd, functions and exit affect your session.
cat > setenv.sh <<'X'
export APP_ENV=staging
cd /srv/app
X
bash setenv.sh;   echo "$APP_ENV"   # empty, still in the old dir
source setenv.sh; echo "$APP_ENV"   # staging, now in /srv/app

We source libraries and env files; we execute scripts.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Shells, scripts and execution