Using source
The command source
does not run another script. Merely it pulls the contents of this other script into this script, and then runs its content as if it was originally part of the calling script.
It's basically a mechanism to include other script's contents into the same scope as your own.
Using readlink
This command is there in case the original script was invoked through a link.
Using sed
This script is making use of sed to transform the name of the calling script to the name config
.
Example
Say we have this script, named orig.bash
:
#!/bin/bash
printf "exectued as: %s\n" $0
cmd=$(readlink -e $0 | sed "s:[^/]*$:config:")
printf "sourcing as: %s\n" "$cmd"
This program will do 2 things.
print out the value of $0
printf "exectued as: %s\n" $0
print the value of the readlink ...
command
cmd=$(readlink -e $0 | sed "s:[^/]*$:config:")
printf "sourcing as: %s\n" "$cmd"
Now let's create a link to this script, link2orig.bash
. So we have the following files now in our directory:
# creates link
$ ln -s orig.bash link2orig.bash
# results after
$ ls -l
total 4
lrwxrwxrwx 1 saml saml 9 Sep 5 06:23 link2orig.bash -> orig.bash
-rwxrwxr-x 1 saml saml 126 Sep 5 06:31 orig.bash
Now watch what happens
So now when we run our example script using either it's real name or the link, we're still able to substitute into the caller's argument the string config
. Which is another file that has configuration information for our script, that we're sourcing.
$ ./orig.bash
executed as: ./orig.bash
sourcing as: /home/saml/tst/89518/config
$ ./link2orig.bash
executed as: ./link2orig.bash
sourcing as: /home/saml/tst/89518/config
If you'll notice, one of the advantages to this approach is that it's extremely tolerant of being called in different ways and from different locations on the system.
$ ../89518/orig.bash
executed as: ../89518/orig.bash
sourcing as: /home/saml/tst/89518/config
$ ../89518/link2orig.bash
executed as: ../89518/link2orig.bash
sourcing as: /home/saml/tst/89518/config