Skip to content

Latest commit

 

History

History
219 lines (172 loc) · 2.91 KB

File metadata and controls

219 lines (172 loc) · 2.91 KB

Bash Scripting CheatSheet

A comprehensive guide covering essential Bash scripting commands for automation, system administration, and DevOps tasks.

Table of Contents

Getting Started

Run a Bash script:

./script.sh

Make a script executable:

chmod +x script.sh

Run Bash interactively:

bash

Variables & Data Types

Define a variable:

variable="Hello, Bash"
echo $variable

Read user input:

read -p "Enter name: " name
echo "Hello, $name"

Operators

Arithmetic operators:

sum=$((5 + 3))
echo $sum

Comparison operators:

[ 5 -eq 5 ]   # Equals
[ 5 -ne 3 ]   # Not Equals
[ 5 -gt 3 ]   # Greater Than

Logical operators:

[ "$a" = "$b" ] && echo "Equal"
[ "$a" != "$b" ] || echo "Not Equal"

Conditional Statements

if [ $x -gt 10 ]; then
    echo "Greater than 10"
elif [ $x -eq 10 ]; then
    echo "Equals 10"
else
    echo "Less than 10"
fi

Loops

For loop:

for i in {1..5}; do
    echo $i
done

While loop:

while [ $x -lt 10 ]; do
    x=$((x+1))
done

Foreach loop:

for item in ${array[@]}; do
    echo $item
done

Functions

Define a function:

function greet() {
    echo "Hello, $1!"
}

Call a function:

greet "Arpit"

Working with Files & Directories

List files in a directory:

ls -l /path

Create a new file:

touch /path/file.txt

Delete a file:

rm /path/file.txt

Working with Processes

List running processes:

ps aux

Kill a process:

kill -9 <PID>

Networking

Check internet connectivity:

ping -c 4 google.com

Get local IP address:

hostname -I

System Administration

Get system info:

uname -a

Restart computer:

sudo reboot

Working with Services

List all services:

systemctl list-units --type=service

Start a service:

sudo systemctl start apache2

Stop a service:

sudo systemctl stop apache2

Error Handling

Try-Catch equivalent in Bash:

if ! ls /nonexistentfile 2>/dev/null; then
    echo "Error: File not found"
fi

Logging

Write to a log file:

echo "Log Entry" >> /var/log/script.log

Bash Modules

List available modules:

compgen -A function

Import a module (source a script):

source script.sh