Explain the difference between executing a script with bash cd.sh
and source cd.sh
cd.sh contains:
#!/bin/sh
cd /tmp
bash
execute the script in a child shell that cannot modify the environment of the invoking shell while source
executes the script in the current shell:
test.sh
#!/bin/sh
export MY_NAME=chucksmash
echo $MY_NAME
Running test.sh:
chuck@precision:~$ bash test.sh
chucksmash
chuck@precision:~$ echo $MY_NAME
chuck@precision:~$ source test.sh
chucksmash
chuck@precision:~$ echo $MY_NAME
chucksmash
chuck@precision:~$
In bash, commands that look like source script.sh
(or . script.sh
) run the script in the current shell, regardless of the #!
line.
Therefore, if you have a script (named script.sh
in this example):
#!/bin/bash
VALUE=1
cd /tmp
This would print nothing (because VALUE
is null) and not change your directory (because the commands were executed in another instance of bash):
bash script.sh
echo $VALUE
This would print 1
and change your directory to /tmp
:
source script.sh
echo $VALUE
If you instead had this script (named script.py
in this example):
#!/usr/bin/env python
print 'Hello, world"
This would give a WEIRD bash error (because it tries to interpret it as a bash script):
source shell.py
This would *also *give a WEIRD bash error (because it tries to interpret it as a bash script):
bash shell.py
This would print Hello, world
:
./shell.py # assuming the execute bit it set