What is the difference between sh and source?
source: source filename [arguments]
Read and execute commands from FILENAME and return. The pathnames
in $PATH are used to find the directory containing FILENAME. If any
ARGUMENTS are supplied, they become the positional parameters when
FILENAME is executed.
And for man sh:
NAME
bash - GNU Bourne-Again SHell
SYNOPSIS
bash [options] [file]
COPYRIGHT
Bash is Copyright (C) 1989-2004 by the Free Software Foundation, Inc.
DESCRIPTION
Bash is an sh-compatible command language interpreter that executes commands read from the standard input or from a file. Bash also incorporates
useful features from the Korn and C shells (ksh and csh).
Bash is intended to be a conformant implementation of the IEEE POSIX Shell and Tools specification (IEEE Working Group 1003.2).
When you call
sourceor.(the one is an alias to the other.sourcecmd not POSIX – kind of bashism), you load and execute a shell script into the current shell process. So you canWhen you call
sh, you initiate a fork (sub-process or child) that runs a new session of/bin/sh(which is often a symbolic link tobash). In this case, environment variables set by the sub-script would be dropped when the sub-script terminate.Caution:
shcould be a symlink to another shell.Practical sample
For example, if you want to change current working directory by a specific manner, you could not do
This won’t do what you expect:
because current working dir is part of environment and
myCd2Doc.shwould run in a subshell.But:
Same, for declaring a function:
Have a look at
mycdfunction!! (With bash completion based on Associative Array).Execution level
$SHLVLRecursion (when a script run from itself)
A little futher
( Current PID (
$$== process Id) are same identifier than SID (session ID). It’s not alway true.)Dot
.is an alias ofsource. So the only difference between two command areslashreplaced byspace.And a final test:
… You may notice a different behaviour between the two syntaxes. 😉