
What Is a Bash Script?
A Bash script is simply a text file containing a sequence of Bash commands. Instead of typing commands manually every time, you can write them once in a file and execute them whenever you want.
Step 1: Creating a .sh File
To get started, open your terminal and follow these steps:
• Create a file:
touch hello.sh
This creates an empty Bash script named hello.sh.
• Open it with a text editor:
You can use nano, vim, or any GUI-based editor.
nano hello.sh
• Write a simple script:
#!/bin/bash
echo “Hello, Hacklivly! Welcome to Bash scripting.”
• The Shebang Line: #!/bin/bash
The first line in a Bash script often begins with:
#!/bin/bash
This is called the shebang. It tells the system which interpreter to use to run the script.
#! is a special character sequence that tells the kernel to use the specified path as the interpreter.
/bin/bash is the absolute path to the Bash shell.
This ensures that your script runs consistently with the Bash interpreter regardless of the user’s default shell.
Tip: You can also use /usr/bin/env bash to make it more portable across different systems.
Step 2: Making Your Script Executable
Just creating the file isn’t enough — you need to give it execute permissions.
chmod +x hello.sh
This command makes the script executable for the user.
You can now run your script like this:
./hello.sh
Output:
Hello, Hacklivly! Welcome to Bash scripting.
Running vs Sourcing a Bash Script
There are two ways to run a Bash script, and they behave slightly differently.
- Running (Recommended)
You run the script as an independent process:
./hello.sh
or
bash hello.sh
This executes the script in a new shell. Any variables or changes made inside the script do not affect your current terminal session.
- Sourcing (Runs in current shell)
source hello.sh
or
. hello.sh
This does not spawn a new shell — it executes the script in your current session. Useful when:
You want to define environment variables or functions you can use after execution.
You want to make directory changes (cd) persist.
Example:
script.sh
#!/bin/bash
cd /tmp
./script.sh → Changes directory in child shell (not reflected in current shell).
source script.sh → Changes directory in current shell.
∆ Practice Time
Create a script that greets a user:
#!/bin/bash
echo “What’s your name?”
read name
echo “Hello, $name! You’re now learning Bash scripting at Hacklivly.”
Save it as greet.sh, make it executable, and run:
chmod +x greet.sh
./greet.sh