0
0
Bash Scriptingscripting~15 mins

Function libraries (sourcing scripts) in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Function Libraries by Sourcing Scripts in Bash
📖 Scenario: You are working on a bash script project where you want to reuse some useful functions stored in a separate file. This helps keep your scripts clean and organized, just like having a toolbox with tools ready to use.
🎯 Goal: Learn how to create a bash function library in one script file and then use source to include those functions in another script. Finally, call the functions to see their output.
📋 What You'll Learn
Create a bash script file named functions.sh with two simple functions.
Create a main bash script named main.sh that sources functions.sh.
Call the sourced functions from main.sh and print their outputs.
💡 Why This Matters
🌍 Real World
In real projects, you often keep reusable bash functions in separate files. This helps you avoid rewriting code and keeps your scripts clean.
💼 Career
Knowing how to source scripts and use function libraries is important for system administrators, DevOps engineers, and anyone automating tasks with bash.
Progress0 / 4 steps
1
Create the function library script
Create a bash script file named functions.sh that defines two functions: greet which prints "Hello, friend!" and farewell which prints "Goodbye, friend!". Write the exact function definitions with these names and messages.
Bash Scripting
Need a hint?

Use the syntax function_name() { commands } to define functions in bash.

2
Create the main script and source the function library
Create a bash script file named main.sh. Inside it, use source ./functions.sh to include the functions from functions.sh. This will let you use the functions defined there.
Bash Scripting
Need a hint?

Use source ./functions.sh or . ./functions.sh to include the functions.

3
Call the sourced functions in the main script
In main.sh, after sourcing functions.sh, call the functions greet and farewell by writing their names on separate lines.
Bash Scripting
Need a hint?

Simply write the function names greet and farewell on separate lines to call them.

4
Run the main script and see the output
Run the main.sh script in your terminal. It should print the greeting and farewell messages from the sourced functions. Write a bash main.sh command and observe the output.
Bash Scripting
Need a hint?

Use the command bash main.sh in your terminal to run the script.