A
command built into every
*n?x shell,
"." (pronounced "
source") will read text from the file named by its first command-line argument
and treat it as input to the shell. This is similar to running the file
as a
shell script, but instead of commands being run in a separate shell
process, they are run in the current shell process. Any additional command-line
parameters are treated as parameters to the script being run.
While the technique conserves the number of active processes, there
is a far more important reason to "source" a script instead of running
it in a separate process: to use the script to set an environment variable
in the calling shell, or to define a shell function in the calling shell.
For example, here's a little shell to add validated directory names
to the PATH environment variable without duplicating the path name in
the string:
#!(@) /bin/sh
# ---------- file name -- addpath ---------
addpath_ec=0
for d in $@
do
if [
then case "::$PATH::"
in
*:$d:*) ;;
*) PATH=$PATH:$d
;;
esac
else echo "$d is not a
directory" >&2
addpath_ec=1
fi
done
export PATH
if [ "$addpath_ec" -eq '0' ]
then unset addpath_ec
true
else unset addpath_ec
false
fi
You would invoke the script by typing
. addpath path
at the command-line prompt. An example session might go:
$ echo $PATH
.:/bin:/usr/bin
$ . addpath i_dont_exist
i_dont_exist is not a directory.
$ echo $?
1
$ . addpath /usr/local/bin
$ echo $?
0
$ echo $PATH
.:/bin:/usr/bin:/usr/local/bin