Shell Scripting for Beginners: Your First Bash Script on Linux
Edited by Dev Kilaru, Senior Data Analyst. How we make our content
Introduction
A shell script is a text file of commands that the shell runs for you, in order. Anything you can type in a terminal you can save in a script and run again, which is how system administrators, developers, and data engineers automate backups, deployments, log checks, and data preparation on Linux and Unix systems. This course teaches Bash, the shell found on nearly every Linux server, with notes on where macOS and other shells differ. This first lesson gets you a working shell, writes your first script, and explains the three things every beginner trips over: the shebang line, file permissions, and exit codes.
Prerequisites
- A Linux or macOS computer, or Windows with WSL (Windows Subsystem for Linux)
- A terminal window
- No programming experience is required
Step-by-Step Guide
Step 1: Know what the shell is
The shell is the program that reads the commands you type and runs them. Bash, short for Bourne Again Shell, is the default on most Linux distributions, while macOS defaults to zsh, which behaves almost the same for everyday commands. The original Bourne shell, called sh, defines the portable baseline that Bash extends. On Windows the simplest route is WSL, which gives you a real Linux shell, and Git Bash is a lighter option for practice. Check what you have with the commands below.
echo "$SHELL"
bash --version
uname -sStep 2: Try the commands you will automate
A script is just commands you already know, saved in order, so practice a few in the terminal first. The pwd command prints where you are, ls lists files, cd changes folder, mkdir creates a folder, and echo prints text. Make a practice folder so your experiments stay in one place and are easy to delete later.
mkdir -p ~/shell-practice
cd ~/shell-practice
pwd
echo "Hello from the terminal"
ls -lStep 3: Write your first script
Create a file named hello.sh in any text editor, such as nano, vim, or VS Code. The first line, #!/usr/bin/env bash, is called the shebang. When you run the file directly, the operating system reads this line to learn which interpreter should execute the rest. Using env finds bash on the user's PATH, which works even on systems where bash is not installed in /bin. Any later line that starts with a hash sign is a comment that the shell ignores.
#!/usr/bin/env bash
# hello.sh - print a greeting and a few facts about the system
echo "Hello, CaliberTek!"
echo "Today is $(date +%A)"
echo "You are logged in as $USER on $(hostname)"Step 4: Make it executable and run it
A new file is not executable by default, which is a safety feature. The chmod +x command adds the execute permission. You then run the script with ./hello.sh, where the leading dot-slash means the current folder. It is required because the current folder is not on your PATH, so a file with a common name cannot run by accident. You can also skip the permission step by handing the file to Bash directly. If you see the message Permission denied, a missing execute bit is the usual cause.
chmod +x hello.sh
./hello.sh
# or, without the execute bit:
bash hello.sh
ls -l hello.sh # -rwxr-xr-x means the file is executableStep 5: Print with echo and printf
The echo command is the quick way to print a line. The printf command gives you control over formatting and behaves the same on every system, so it is the better choice when output must be exact, such as in reports. It does not add a newline by itself, so you include the newline escape in the format string. Single quotes print text exactly as written, while double quotes let the shell replace variables and commands with their values.
echo "Plain line"
echo -n "No newline at the end"
printf "%s has %d items\n" "cart" 3
printf "%-10s %5.2f\n" "Total:" 19.5
echo 'Single quotes: $HOME is not expanded'
echo "Double quotes: $HOME is expanded"Step 6: Understand exit codes
Every command finishes with an exit status, a number from 0 to 255 stored in the special variable $? right after it runs. Zero means success and anything else means failure. This is the reverse of many programming languages, and it matters because if statements, the && and || operators, cron, and CI pipelines all decide what to do from exit codes. A script returns the status of its last command, or whatever number you give to exit. Use a non-zero exit when something goes wrong so that whoever called your script can detect the failure.
ls /tmp
echo "ls exit code: $?" # 0
ls /does-not-exist
echo "ls exit code: $?" # non-zero (2 with GNU ls)
true; echo $? # 0
false; echo $? # 1Step 7: Run your scripts from anywhere
To run your scripts by name, put them in a folder on your PATH. A common choice is a bin folder in your home directory. Add that folder to PATH in your ~/.bashrc file (or ~/.zshrc on macOS) and open a new terminal or reload the file. After that, the script runs from any directory without the dot-slash. It is also worth keeping your scripts in a Git repository so you can see what changed and restore an older version.
mkdir -p ~/bin
cp hello.sh ~/bin/hello
echo 'export PATH="$HOME/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc
helloFAQs
- Do I need the .sh extension on a script?
- No. Linux decides how to run a file from its permissions and its shebang line, not from its name. The .sh extension is a convention that helps editors and people recognize scripts. Commands that you install on your PATH are often named without any extension.
- What is the difference between sh and bash?
- The name sh refers to the standard POSIX shell, and on some systems such as Debian and Ubuntu it points to a smaller shell called dash. Bash is a superset that adds arrays, the double-bracket test, and many conveniences. If your script uses Bash features, give it a bash shebang and run it with bash instead of sh.
- Why do I get a bad interpreter error with a strange ^M in it?
- The file almost certainly has Windows line endings. The invisible carriage return at the end of the shebang line becomes part of the interpreter name, so the system cannot find it. Convert the file with the dos2unix command, or set your editor to save files with Unix (LF) line endings.
Summary
You learned what the shell and a script are, wrote hello.sh with a shebang line, made it executable and ran it, printed output with echo and printf, read exit codes, and put your scripts on your PATH. These basics are the foundation for everything that follows. In the next lesson you will learn variables, quoting, and reading input so your scripts can work with data that changes from run to run.
Related tutorials
- Schedule and Debug Shell Scripts: cron, bash -x, and Portability
- Shell Scripting Project: A Backup Script with Rotation and a Log Report
- Writing Safe Bash Scripts: set -euo pipefail, getopts, and trap
- Shell Pipes, Redirection, grep, sed, and awk for Text Processing
- Bash Loops, Arrays, and Functions Explained
Comments
Log in or create a free account to join the discussion.