Bash Shell Scripting for Beginners | Complete Guide
bash scripting, shebang, variables, if else, for loop, while loop, functions, chmod +x
Bash Shell Scripting for Beginners
Shell scripting is one of the most powerful tools available in Linux. A bash script is a plain text file containing a sequence of commands that the shell executes in order. Scripts automate repetitive tasks, enforce consistent processes, and allow you to build complex workflows from simple Linux commands. Bash scripting is an essential Linux skill for system administrators, DevOps engineers, and developers.
Creating Your First Script
Every bash script begins with a shebang line that tells the system which interpreter to use. Create the file, add the shebang, write commands, make it executable, and run it.
#!/bin/bash
echo "Hello from my first shell script!"
date
uname -anano hello.sh
chmod +x hello.sh
./hello.shVariables in Bash
Variables in bash are untyped and set without spaces. Reference them with a dollar sign. Double quotes allow variable expansion while single quotes treat everything literally.
#!/bin/bash
NAME="Alice"
GREETING="Hello, $NAME!"
echo $GREETING
echo "Current user: $USER"
echo "Today is: $(date)"The $(command) syntax is command substitution — it executes the command and inserts its output inline.
Conditionals with if/else
Bash uses if/then/else/fi syntax for conditional logic. Square brackets are the test command, and spacing around them is required.
#!/bin/bash
FILE="/etc/hosts"
if [ -f "$FILE" ]; then
echo "File exists: $FILE"
else
echo "File not found: $FILE"
fi
if [ $# -eq 0 ]; then
echo "No arguments provided"
fiLoops in Bash
The for loop iterates over a list of items. The while loop runs while a condition is true.
#!/bin/bash
for i in 1 2 3 4 5; do
echo "Number: $i"
done
for FILE in /var/log/*.log; do
echo "Log file: $FILE"
done
COUNT=0
while [ $COUNT -lt 5 ]; do
echo "Count: $COUNT"
COUNT=$((COUNT + 1))
doneFunctions
Functions allow you to group commands and reuse them throughout your script.
#!/bin/bash
greet_user() {
local USERNAME=$1
echo "Hello, $USERNAME! Today is $(date +%A)."
}
greet_user "Alice"
greet_user "Bob"The $1, $2, etc. are positional parameters — the arguments passed to the script or function. The local keyword keeps variables scoped to the function.
