Shell scripting, difference of "source script.sh" and "./script.sh"
I added created a script /opt/path.sh to add paths for some programs in /opt. The content of the script is:
But it doesn't execute the script unless I execute it with "source /opt/path.sh"
I have found something (http://programming.itags.org/unix-li...ramming/81171/). According to this, the change is only at run-time. But I thought executing "export" make it global?
Can somebody explain it please?
you should not put a script directly in /opt, that's a really bad place to put anything other than other directories.
source does not run the file, it just inserts it into the current script, and evaluates it as part of the current script. This is typically used for adding in standard functions. It doesn't look like your script deserves it's own file anyway, just add it to your path directly.
This (quote from the link you posted):
- If you execute a script a new shell is created first. The subsequent export var makes the var available in that new shell and its sub-shells.
Hope this clears things up a bit.
It's all about shells. Initially there is only one process running,
and it spawns new processes, including a set of processes that let
you log in.
After you log in, you are running a process with your login shell,
probably bash. When you type most commands, the current shell pauses
while a subshell is created to run the command. After the command
finishes the subshell quits and you are returned to your original shell.
Within your shell you have variables set, and some of them are
exported. The ones that are exported are created in all subshells
automatically. The ones that are not exported do not get created.
So exporting doesn't really make a variable global. It just means
that variable is created in any subshells.
Incidentally, there is one notable command that doesn't create a
subshell, and that is source. When you source a command, the
command is run in the current shell.
If you want your script to work, add "source /opt/path.sh" to
/etc/profile or move the script to /etc/profile.d.
|All times are GMT -5. The time now is 11:10 AM.|