Introduction
Shell scripting automates repetitive tasks in Linux. Bash (Bourne Again Shell) is the most common shell for writing scripts. Scripts combine commands, variables, and logic into reusable programs.
Your First Script
#!/bin/bash
# This is a comment
echo "Hello, World!"
echo "Current date: $(date)"
Save as hello.sh, make it executable with chmod +x hello.sh, and run with ./hello.sh.
Variables and Input
#!/bin/bash
NAME="CodePath"
echo "Welcome to $NAME"
# Read user input
read -p "Enter your name: " USERNAME
echo "Hello, $USERNAME!"
Conditional Statements
#!/bin/bash
if [ -f "/etc/passwd" ]; then
echo "File exists"
elif [ -d "/tmp" ]; then
echo "Directory exists"
else
echo "Not found"
fi
Loops
# For loop
for file in *.txt; do
echo "Processing $file"
done
# While loop
count=0
while [ $count -lt 5 ]; do
echo "Count: $count"
((count++))
done
Functions
#!/bin/bash
greet() {
local name=$1
echo "Hello, $name!"
return 0
}
greet "World"
Summary
Shell scripting enables powerful automation in Linux. Combine variables, conditionals, loops, and functions to create robust automation scripts for system administration and DevOps tasks.
YouTip