When compiling applications from source code using make or cmake the instructions usually say,
source <some path> <parameter>
export <some text>
Also, a lot of time LD_LIBRARY_PATH comes up, being used with export.
Whats the difference of source and export ? Why we need them ?
1 Answer
The shell commands source and export are really different things. In short:
source
When you call a shell script the normal way (say with ./myscript.sh or sh myscript.sh), it will be executed in its own process context (a new process environment), so all variables set in the script will not be available in the calling shell. When executing a script using the source command, it will be executed within the context of the calling script. This way you are able to set environment variables by calling source myscript.
export
Environment variables are usually only valid in the (local) context of the current process. So, if you execute something (script or program) which requests a new process environment, the local environment will not be seen within the new process. To pass environment values to a child process, you have to 'export' them by preceeding the assignment with export, e.g. export VAR=value.
export LD_LIBRARY_PATH
The special environment variable LD_LIBRARY_PATH defines the path where loadable libraries are searched for (similar to the PATHvariable, which defines where to look for executables). By default libraries are searched in /lib, /usr/lib and the like. Libraries installed in non-standard directories (e.g. /opt/program/lib) can only be loaded when these paths are additionally defined by export LD_LIBRARY_PATH=/opt/program/lib in this example. You need export here, as this must be known to the new process environment your program is running in.
Persistence
The process environment exists as long as the process is running; this also holds true for the environment variables (when not unset explicitly). If the process is killed (e.g. by closing the terminal window), usually all subprocesses will be killed as well and the environment(s) are deleted. More precisely, this depends on how the child process reacts on SIGHUP. If it does not, it will be running further as child of the user process (e.g. /sbin/upstart --user) or the init process (PID=1).
One way to have subprocesses overcome the killing of the parent process is to release them from the parent process by using nohup command (see man nohup), which will not pass SIGHUP to the child, and releasing the process to the background:
nohup <progname> &
will detach the process from the parent, assign STDIN to /dev/null and STDOUT to ./nohup.out.