Create Your First Shell Script: Hello World
Summary: Write and run your very first .sh
file in Bash.
Learning to write shell scripts is the first step towards mastering automation and efficient command-line workflows. In this guide, you’ll create your very first shell script using Bash: the classic “Hello World”.
What Is a Shell Script?
A shell script is a plain text file that contains commands you would normally enter in a terminal, executed in sequence by a shell interpreter. Bash is the most popular shell on Linux and macOS, though it’s also available for Windows.
Prerequisites
- A Unix-like operating system (Linux, macOS, or Windows Subsystem for Linux).
- A text editor (like
nano
,vim
, or even VS Code). - Access to a terminal.
Step 1: Open Your Terminal
Launch a terminal window. On macOS and Linux, look for “Terminal” in your applications. On Windows, use Windows Subsystem for Linux (WSL) or Git Bash.
Step 2: Create a New Script File
Use your editor of choice to create a new file called hello.sh
. For example, in your terminal:
nano hello.sh
Or with vim
:
vim hello.sh
Step 3: Write Your Shell Script
Type the following lines:
#!/bin/bash
# This script prints "Hello, World!" to the terminal
echo "Hello, World!"
Explanation:
#!/bin/bash
: Called a "shebang", tells the system to use the Bash shell to interpret this script.- Lines starting with
#
are comments for humans; they are ignored by Bash. echo "Hello, World!"
prints the text to the terminal.
Save and exit the editor (in nano
, press CTRL+O
to save, CTRL+X
to exit).
Step 4: Make the Script Executable
Before you can run your new script, give it execute permission:
chmod +x hello.sh
Step 5: Run Your Script
Now, execute your script like this:
./hello.sh
You should see:
Hello, World!
Troubleshooting
- If you get
command not found
orpermission denied
, double check you typed the commands correctly and gave execute permission. - If you see “bad interpreter: No such file or directory”, ensure your shebang line is exactly
#!/bin/bash
and Bash is installed at/bin/bash
.
What Next?
Now you've created and run your first shell script! Here are some ideas for experiments:
- Change the message in the
echo
statement. - Add more
echo
lines. - Try using variables:
#!/bin/bash name="Student" echo "Hello, $name!"
Conclusion
Shell scripts are powerful tools for automating everyday tasks. With just a few lines, you can translate any terminal command sequence into a reusable script. This “Hello World” is just the start of your shell scripting journey — happy automating!
Want to learn more? Check out resources on Bash scripting and command-line fundamentals to expand your skills!