A comprehensive guide covering essential Bash scripting commands for automation, system administration, and DevOps tasks.
- Getting Started
- Variables & Data Types
- Operators
- Conditional Statements
- Loops
- Functions
- Working with Files & Directories
- Working with Processes
- Networking
- System Administration
- Working with Services
- Error Handling
- Logging
- Bash Modules
Run a Bash script:
./script.shMake a script executable:
chmod +x script.shRun Bash interactively:
bashDefine a variable:
variable="Hello, Bash"
echo $variableRead user input:
read -p "Enter name: " name
echo "Hello, $name"Arithmetic operators:
sum=$((5 + 3))
echo $sumComparison operators:
[ 5 -eq 5 ] # Equals
[ 5 -ne 3 ] # Not Equals
[ 5 -gt 3 ] # Greater ThanLogical operators:
[ "$a" = "$b" ] && echo "Equal"
[ "$a" != "$b" ] || echo "Not Equal"if [ $x -gt 10 ]; then
echo "Greater than 10"
elif [ $x -eq 10 ]; then
echo "Equals 10"
else
echo "Less than 10"
fiFor loop:
for i in {1..5}; do
echo $i
doneWhile loop:
while [ $x -lt 10 ]; do
x=$((x+1))
doneForeach loop:
for item in ${array[@]}; do
echo $item
doneDefine a function:
function greet() {
echo "Hello, $1!"
}Call a function:
greet "Arpit"List files in a directory:
ls -l /pathCreate a new file:
touch /path/file.txtDelete a file:
rm /path/file.txtList running processes:
ps auxKill a process:
kill -9 <PID>Check internet connectivity:
ping -c 4 google.comGet local IP address:
hostname -IGet system info:
uname -aRestart computer:
sudo rebootList all services:
systemctl list-units --type=serviceStart a service:
sudo systemctl start apache2Stop a service:
sudo systemctl stop apache2Try-Catch equivalent in Bash:
if ! ls /nonexistentfile 2>/dev/null; then
echo "Error: File not found"
fiWrite to a log file:
echo "Log Entry" >> /var/log/script.logList available modules:
compgen -A functionImport a module (source a script):
source script.sh