What is the difference between `./script.sh`, `bash script.sh` and `source script.sh`?
BeginnerConceptShells, scripts and execution
Answer
./script.shneeds the execute bit, honours the shebang and runs in a new process.bash script.shruns 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 andexitaffect 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.
More on Shells, scripts and execution
What is a shell, and how is Bash different from sh, dash and zsh?BeginnerWhat does the shebang line do, and why prefer `#!/usr/bin/env bash` over `#!/bin/bash`?BeginnerWhat happens when you type a command name? How does Bash decide what to run?AdvancedWhy must `cd`, `export` and `read` be builtins rather than external programs?IntermediateWhat is the difference between a login, interactive and non-interactive shell, and which startup files run?IntermediateWhat does `exec` do in a script? Give two uses.Advanced