0x90 0x90 - 5 months ago 24
Bash Question

What is the difference between `sh` and `source`?

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).

Answer

When you call source (or its alias .), you insert the script in the current bash process. So you could read variables set by the script.

When you call sh, you initiate a fork (sub-process) that runs a new session of /bin/sh, which is usually a symbolic link to bash. In this case, environment variables set by the sub-script would be dropped when the sub-script finishes.

Caution: sh could be a symlink to another shell.

One little sample

For example, if you want to change current working directory by a specific manner, you could not do

cat <<eof >myCd2Doc.sh
#!/bin/sh
cd /usr/share/doc
eof

chmod +x myCd2Doc.sh

This won't do what you expect:

cd /tmp
pwd
/tmp
~/myCd2Doc.sh
pwd
/tmp

because current working dir is part of environment and myCd2Doc.sh would run in a subshell.

But:

cat >myCd2Doc.source <<eof
# Shell source file
myCd2Doc() {
    cd /usr/share/doc
}
eof

. myCd2Doc.source
cd /tmp
pwd
/tmp
myCd2Doc
pwd
/usr/share/doc

I wrote a small sample of mycd function.