Just like other programming languages that allow you to include files, Bash scripting also enables you to include (or source) another shell script within your script. This practice is a powerful way to modularize your code and reuse functions, variables, and configurations. It helps keep your scripts organized, readable, and maintainable.

For instance, to include a script named filename.sh in your current script, you can use the following syntax, assuming that filename.sh is in the same directory as your current script:

Syntax

1
source filename.sh

or

1
. filename.sh

The source command (or its synonym .) is commonly used to include and execute the contents of one script within another. This method is ideal for incorporating functions, variables, and configurations.

Example

Suppose you have a script functions.sh containing some useful functions:

1
2
3
4
# functions.sh
greet() {
echo "Hello, $1!"
}

You can include functions.sh in your main script main.sh like this:

1
2
3
4
5
6
7
#!/bin/bash

# Include the functions script
source functions.sh

# Use the function from the included script
greet "World"

When you run main.sh, it will output:

1
2
$ ./main.sh
Hello, World!