Bash – ”Sourcing” script from another script

Karl Auer kauer at biplane.com.au
Tue Jan 6 13:33:12 UTC 2015


On Mon, 2015-01-05 at 18:16 +0100, Johnny Rosenberg wrote:
> Another idea I had, before I read this, was four scripts:
> MainScript.sh
> CalculateVariables.sh
> Script1.sh
> Script2.sh
> 
> MainScript.sh would look something like this:
> #!/bin/bash
> 
> CalculateVariables.sh
> Script1.sh
> Script2.sh
> MoreStuff here or where ever suitable.
> 
> Could that be a reasonable approach?

This runs the separate scripts from inside a main script; it does not
source them. The variable values will not be passed on.

> Script1.sh and Script2.sh could have commants that tells the reader that
> variables are declared and/or calculated in CalculateVariable.sh and that
> MainScript.sh starts all the other scripts, just to make it easier to
> follow.

If you will never run Script1 and Script2 separately, then you should
create a single script out of them. You will then only have to calculate
the variables once, so might as well incorporate that nto the same
single script.

If the process of calculating the variables is independently useful
(i.e., there may one day be a Script3 that also has to calculate the
same variables), or if you need to be able to run Script1 and Script2
independently of each other, then make CalculateVariables into an
independent file and source it from inside the other two.

If running CalculateVariables as a standalone script is pointless, you
can (and should) prevent that happening by NOT making the first line
"#!/bin/sh".

If running it without the proper preparation provided by Script1 or
Script2 is actually dangerous, and you really don't want that to happen,
you can do something like have a secret variable that you set in calling
scripts; if Calculatevariables doesn't see that variable, it refuses to
run. It won't stop someone who is determined to run it, but it will at
least force them to be very deliberate about doing so - no-one will run
it by mistake.

Regards, K.

-- 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Karl Auer (kauer at biplane.com.au)
http://www.biplane.com.au/kauer
http://twitter.com/kauer389

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