UNIX Source Command: Read And Execute Commands From File

What is the use of UNIX source command under bash or any other shell? How do I use source command under UNIX / OS X / Linux operating systems?

Bash shell comes with source command which is used to read and execute commands from given FILENAME and return. If any ARGUMENTS are supplied, they become the positional parameters when FILENAME is executed. This is useful to create your own shell scripting libraries and call them using the source command. The syntax is as follows:

ADVERTISEMENTS

source /path/to/fileName

Create a shell script called functions.sh as follows:

#!/bin/bash
JAIL=/jaildir
 
addusertojail(){
   echo "Adding users..."
}
 
setupjail(){
   echo "Setting up jail"
}

Now create a file called test.sh:

#!/bin/bash
source functions.sh
 
# access $JAIL defined in functions.sh
echo "Jail dir : $JAIL"
 
# call functions
addusertojail
setupjail
🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04

ADVERTISEMENTS
3 comments… add one
  • Vamsi Aug 10, 2010 @ 13:57

    Thanks,
    This if for the first time , I have herd about source command..
    very informative post :)

  • JackS Aug 24, 2010 @ 9:17

    hi, ‘source’ it’s similar to ‘.’.

    ‘.’ is a synonym for ‘source’

  • Vikram Singh May 30, 2011 @ 5:12

    Good Explanation….

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.