Thursday, October 9, 2014

Dot dot-slash to run shell scripts

Let's say you have 2 shell scripts and you want to run them separately and manually, but the second depends on the first. Normally [1] to do this in Linux you type:


[other possible operations]


If the first script sets something for the second script you can have a surprise: the first script didn't have effects and the second one will break. How is it possible?

As well explained here:
Normally, the shell runs a command file in a subshell so that changes to the environment by such commands as cd, set, and trap are local to the command file.
This means that the effect of the first script are inside the subshell and when you come back to your previous shell, running the second script, you will not be able to access what has been set in the subshell.

To avoid this problem this is the correct way to execute the scripts

. ./first_script

[other possible operations]


Notice the dot before ./first_script. It means [2]: run the script in the current environment and then return. In this way the second script will not break, because the first (on which it depends) worked on the current environment.

A real case is when you use Apache Ant to build Java applications. When you set your ant environment in a shell and then you run the command ant to build you Java application, you will have the strange message that says "unable to locale ant", "'ant' is not recognized as an internal or external command”, or something similar. This happens when you used a first script to set your ant environment (ANT_HOME, PATH, etc.) and then you are trying to run the actual ant command, but given that the first script has been executed in a separate subshell you don't have the proper settings in your current environment.



No comments:

Post a Comment