Source command

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
← Shell functions libraryHomeRecursive function →
  • The source command can be used to load any functions file into the current shell script or a command prompt.
  • It read and execute commands from given 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.


  • The syntax is as follows:
source filename [arguments]
source /path/to/ arg1 arg2
source WWWROOT=/apache.jail PHPROOT=/fastcgi.php_jail


Create a shell script called as follows:

   [ $(id -u) -eq 0 ] && return $TRUE || return $FALSE

Save and close the file. You can now call and use function is_root() from using the following syntax in your script called

# Load the using source comamnd

echo "JAIL_ROOT is set to $JAIL_ROOT"

# Invoke the is_root() and show message to user
is_root && echo "You are logged in as root." || echo "You are not logged in as root."

Save and close the file. Run it as follows:

chmod +x

Sample outputs:

JAIL_ROOT is set to /www/httpd
You are not logged in as root.

Our previous example can be updated using source command as follows:

# load function file
source /home/vivek/lsst2/

# local variable
quote="He WHO Sees me in all things, and ALL things in me, is never far from me, and I am never far from him."

# invoke is_root()
is_root && echo "You are a superuser." || echo "You are not a superuser."

# call to_lower() with ${quote}
to_lower ${quote}

A Note About Exit Status

This command returns the status of the last command executed in FILENAME; fails if FILENAME cannot be read. In this example, /etc/init.d/function exists and source using the following command:

source /etc/init.d/function &>/dev/null
echo $?

Sample outputs:


The exit status 0 indicate that source commanded successfully read /etc/init.d/function file. In this example, /etc/init.d/foo does not exists and source using the following command:

source /etc/init.d/foo &>/dev/null
echo $?

Sample outputs:


The exit status 1 indicate that source commanded failed to read /etc/init.d/foo file.

← Shell functions libraryHomeRecursive function →