Harkonnen
Harkonnen

Reputation: 813

Launching an external script with source command

I've been learning shell scripting, by reading good tutorials and reading scripts.

I was reading that script (https://github.com/Ahtenus/minecraft-init/blob/master/minecraft), and these first lines hit me :

if [ -L $0 ]
then
    source `readlink -e $0 | sed "s:[^/]*$:config:"`
else
    source `echo $0 | sed "s:[^/]*$:config:"`
fi

So, these lines launch the script named "config" (where all config values are stored) in the same shell. But why, instead of launching directly the file (with something like "source config", the author of that script reads the name of the original script (whether it is a link or not) and sends the result to sed to replace this name with "config" ?

Thanks for your explanation.

Upvotes: 0

Views: 305

Answers (3)

konsolebox
konsolebox

Reputation: 75488

It simply tries to get the actual directory where the calling script is located by replacing the filename of the calling script (in $0) with config.

If the calling script was called with a link (-L $0), it would also attempt to read the value of the link as well to the actual file.

Alternatively you could read the script like this:

if [ -L "$0" ]
then
    ME=`readlink -e "$0"`
else
    ME=`$0`
fi

MYDIR=`dirname "$ME"`
CONFIG=$MYDIR/config

source "$CONFIG"

Upvotes: 1

devnull
devnull

Reputation: 123508

There are two parts to your question:

the author of that script reads the name of the original script ...

This is essentially a way chosen by the author to ensure that the name of the config file is config. Simple. The script ensures that, whatever be the path to the file supplied, use a file named config.

Moreover, you seemed to be confused about source. source would execute the file in the same context as the current shell.

Upvotes: 0

fedorqui
fedorqui

Reputation: 289725

This code sources the file config contained in the same path of the script real path.

Let's explain the code:

if [ -L $0 ]
then
    source `readlink -e $0 | sed "s:[^/]*$:config:"`
else
    source `echo $0 | sed "s:[^/]*$:config:"`
fi

As you say in your question, if [ -L $0 ] checks if the script name ($0) is a link or not.

readlink -e $0 returns the target of the link:

$ ln -s a mylink
$ ls -la
lrwxrwxrwx  1 me me    1 Sep  5 11:59 mylink -> a
$ readlink -e mylink 
/home/me/test/a

Being /home/something/script.sh the script real path, with sed "s:[^/]*$:config:" will replace everything after last / with config:

$ echo "hjio/hi/hi" | sed "s:[^/]*$:config:"
hjio/hi/config

So what it is doing is to source the file config contained in the same path of the script.

Upvotes: 0

Related Questions