Shell scripting is the secret weapon of every Linux power user and system administrator. With its ability to automate tasks, process data, and manage system operations, itโs a must-have skill in your tech toolkit. In this ultimate guide, weโll break down Linux Shell Scripting, its commands, flags, and best practicesโall in one place.
๐ What Is Shell Scripting?
Shell scripting is a way to automate tasks in Linux by writing scripts composed of various commands. These scripts run in a shell environment, such as Bash, and follow a specific sequence of execution.
โจ Why Learn Shell Scripting?
- Automate repetitive tasks
- Manage system processes
- Perform file operations
- Enhance DevOps workflows
- Simplify complex server management
๐ง Essential Shell Scripting Basics
1. Creating a Script
- Use
.sh
as the file extension. - Start with the shebang
#!/bin/bash
to specify the interpreter. - Make the script executable using
chmod +x script.sh
.
2. Echo Command
echo "Hello, World!" # Similar to print in other languages
Use -n
to keep the output on the same line.
3. Variables & Strings
name="Linux Ninja"
echo "Hello, $name"
echo "Show the dollar sign: \$"
Avoid spaces around the =
when declaring variables.
4. Command Substitution
date=$(date)
echo "Current Date: $date"
โ๏ธ Command Redirection
-
>
: Redirect output to a file (overwrite) -
>>
: Append output to a file -
<
: Redirect input from a file -
|
: Pipe output between commands
Example:
ls -l > filelist.txt # Save list to file
cat filelist.txt | grep "txt" # Filter specific output
Advanced Redirection:
command 2> errorlog.txt # Redirect errors
command &> outputlog.txt # Redirect both output and errors
๐งฎ Math Operations
- Use
expr
for basic math or$(( ))
for arithmetic. - Example:
a=5
b=3
result=$((a+b))
echo "Result: $result"
For floating-point math, use bc
:
echo "scale=2; 5 / 3" | bc
๐ Conditional Statements
If-Then-Else Format:
if [ $a -eq $b ]
then
echo "Equal"
else
echo "Not Equal"
fi
Use []
or [[ ]]
for expressions and -eq
, -lt
, -gt
for comparisons.
Nested If-Else:
if [ $a -gt $b ]
then
echo "A is greater"
elif [ $a -lt $b ]
then
echo "B is greater"
else
echo "Equal"
fi
๐ Loops in Shell Scripting
For Loop:
for file in *
do
echo "Processing $file"
done
While Loop:
count=1
while [ $count -le 5 ]
do
echo "Count: $count"
count=$((count+1))
done
Until Loop:
count=1
until [ $count -gt 5 ]
do
echo "Count: $count"
count=$((count+1))
done
๐ฅ Reading User Input
read -p "Enter your name: " user
echo "Hello, $user"
Use -t
to set a timeout and -s
to hide the input.
โก Advanced Topics: File Descriptors & Redirection
-
0
: Standard input (STDIN) -
1
: Standard output (STDOUT) -
2
: Standard error (STDERR)
Redirect errors:
command 2> errorlog.txt
Use exec
for persistent redirections:
exec 1>output.txt # Redirect STDOUT
exec 2>error.txt # Redirect STDERR
Close a file descriptor:
exec 1>&-
๐ Command-Line Arguments
-
$0
: Script name -
$1, $2...
: Arguments passed -
$#
: Number of arguments -
$@
: All arguments as separate words -
$*
: All arguments as a single word
Example:
./script.sh arg1 arg2
Access arguments inside the script:
echo "First Arg: $1"
echo "All Args: $@"
๐ ๏ธ Command-Line Options with Getopts
while getopts "a:b:c:" opt; do
case $opt in
a) echo "Option A: $OPTARG" ;;
b) echo "Option B: $OPTARG" ;;
c) echo "Option C: $OPTARG" ;;
*) echo "Invalid option" ;;
esac
done
๐ Data Management with Tee & Temp Files
Use tee
to split output:
command | tee output.txt
Create temporary files:
mktemp tempfile.XXXXXX
๐ Conclusion
Mastering shell scripting can significantly boost your productivity and system administration skills. With this guide, youโre well on your way to becoming a Linux Automation Ninja! ๐ช
Ready to Level Up? Share your favorite shell tips below or let me know which topic youโd like to dive deeper into! ๐ป๐ฅ
Top comments (2)
Pretty good introduction.
Specific comments:
Using the file name extension is purely optional. I'm not aware of anything that pays attention to
.sh
.date=$(date)
makes the date command subsequetly unavailable by default. It's better to use unique names for variables.cat filelist.txt | grep "txt"
is an example of a useless cat. A better example might begrep "txt" filelist.txt | less
echo "scale=2; 5 / 3" | bc
using scale is a nice touch. I didn't know about that.count=$((count+1))
is fine, but I prefer$((count++))
Use -n to keep the output on the same line.
could be clearer. - Use -n to suppress the newline at the end so that further output can be appended to the same output line.$0: Script name
is almost right. It's the path used to invoke the script on the command line. To just get the base name of the script, something likescript_name="${0##*/}"
does the trick.
Really small nit: File descriptor names like
STDIN
probably shouldn't be upper case because you can actually use them as/dev/stdin
if desired.Thank Joe for your valuable info and I will take these into my tool kit ๐