Bash – ”Sourcing” script from another script

Karl Auer kauer at
Tue Jan 6 15:01:31 UTC 2015

On Tue, 2015-01-06 at 14:53 +0100, Johnny Rosenberg wrote:
> So running a script with source means that the ”#!/bin/sh” (or in my case
> ”#!/bin/bash”) in goes for the sourced script too,
> automatically?

Not sure I understand the question, so I'll answer with a description of
how things work ;-)

Terminology: The script doing the sourcing is the main script, the
script being sourced is the source script.

The source script is syntactically inserted into the main script at the
point where it is sourced. It is not called, it is not executed, it does
not get a separate shell process. It becomes part of the main script.
Whatever is interpreting and executing the main script will interpret
and execute the source script too.

Any line in the source script that starts with a "#" is treated as a
comment and ignored. "#!/bin/sh" is only meaningful if it is the very
first line of a script. It is not special in a source file, because
there is no way it can ever be the first line.

If you run these commands...

   echo ". /tmp/" > /tmp/
   echo '#!/bin/dash' > /tmp/
   echo "ps ax | grep \$\$ | grep -v grep | awk '{print \$5}'"
>> /tmp/
   chmod u+x /tmp/ /tmp/
   /tmp/ ; /tmp/ should see this output:

   bash, run on its own, reports dash. But when sourced by, it reports bash. That is, the first line of is
ignored when is sourced, even though it is the first line of
a source script that is sourced in the first line of a main script.

BTW this also tells you that any executable text file will be treated as
a bash script by bash if it doesn't have another interpreter specified
in the first line.

> Does this mean that you can't source, for instance a Python script from a
> bash script? Or does omitting that line only mean ”nothing is changed, keep
> going”?

You can source anything you like, but if the source file is not correct
for whatever is interpreting and executing the main file, then the
source file will cause errors. bash can't interpret python. Yet :-) To
run python you need a new process, running a python interpreter.

Regards, K.

Karl Auer (kauer at

GPG fingerprint: 3C41 82BE A9E7 99A1 B931 5AE7 7638 0147 2C3C 2AC4
Old fingerprint: EC67 61E2 C2F6 EB55 884B E129 072B 0AF0 72AA 9882

More information about the ubuntu-users mailing list