Skip to main content

Bash & Linux Cheat Sheet

Linux: The Operating System for Developers & Builders

Free, open-source, runs everything from your laptop to cloud servers. Master it once, use it everywhere.


What It Is (Simple)

Think of it as the universal building block of software infrastructure.

  • Operating System: Kernel + tools + packages + freedom
  • Created: 1991 by Linus Torvalds (still maintained by global community)
  • Philosophy: Free, open-source, user controls everything
  • Runs: Laptops, servers, IoT devices, phones (Android), cloud infrastructure, embedded systems

Why it matters for builders:

  • ✅ Free (no licensing costs)
  • ✅ Open-source (see and modify anything)
  • ✅ Runs your code the same way locally as in production
  • ✅ Industry standard (AWS, Google Cloud, Azure all run Linux)
  • ✅ Powerful command-line tools for automation
  • ✅ Scales from Raspberry Pi to 10,000-server clusters

Core Linux Concepts

1. The Kernel

The core. Manages:

  • CPU scheduling (which program gets to run)
  • Memory management (RAM allocation)
  • Process management (running programs)
  • File systems (storage)
  • Networking (TCP/IP stack)
  • Device drivers (hardware access)

You don't interact with the kernel directly. It just works. But when things break, understanding the kernel helps.

2. File System Hierarchy

/                    ← Root (top-level)
├── /home/ ← User files (your code, documents)
├── /var/ ← Logs, databases, runtime data
├── /etc/ ← Configuration files
├── /bin/ ← Essential commands
├── /usr/bin/ ← Installed programs
├── /opt/ ← Third-party software
├── /tmp/ ← Temporary files (deleted on reboot)
└── /root/ ← Root user's home (dangerous!)

Important:

  • Everything is a file (even devices are files in /dev)
  • Permissions matter (rwx = read/write/execute)
  • /etc is where config files live (understand this for production debugging)
CommandExplanation
pwdPrint current directory
lsList directory contents
ls -laList all files with details
ls -lhHuman readable sizes
cd dirChange directory
cd ..Move one directory up
cd ~Go to home directory
cd -Go to previous directory
treeShow directory structure

File & Directory Operations

CommandExplanation
touch fileCreate empty file
mkdir dirCreate directory
mkdir -p a/b/cCreate nested directories
cp file1 file2Copy file
cp -r dir1 dir2Copy directory
mv old newMove or rename file
rm fileDelete file
rm -r dirDelete directory
rm -rf dirForce delete directory

Viewing Files

CommandExplanation
cat filePrint file contents
less fileScrollable viewer
head fileFirst 10 lines
head -n 50 fileFirst 50 lines
tail fileLast 10 lines
tail -f logFollow log updates
wc fileCount lines, words, bytes

Searching Files & Content

grep (search inside files)

CommandExplanation
grep "text" fileSearch text
grep -i "text" fileCase insensitive search
grep -n "text" fileShow line numbers
grep -c "text" fileCount matches
grep -r "text" .Recursive search

Example:

grep -i "error" app.log

find (search files)

CommandExplanation
find . -name "*.log"Find log files
find /path -type fFind files
find /path -type dFind directories
find /logs -mtime -1Modified in last 24 hours
find /logs -size +100MFiles larger than 100MB
find /logs -name "*.log" -exec grep -l "ERROR" {} \;Find logs containing ERROR

These log-analysis commands are heavily used in DevOps troubleshooting.


Text Processing (Core Automation Tools)

CommandExplanation
sort fileSort lines
uniqRemove duplicates
cut -d',' -f1Extract column
awk '{print $1}'Print column
sed 's/a/b/g'Replace text

Example pipeline:

cat logs.txt | grep ERROR | sort | uniq

File Permissions (IMPORTANT)

Linux permissions follow:

rwx rwx rwx
│ │ │
│ │ └── others
│ └────── group
└────────── owner

Each permission has numeric values:

PermissionValue
Read4
Write2
Execute1

Example combinations:

CommandMeaning
chmod 755 fileOwner full, others read+execute
chmod 644 fileOwner read/write, others read
chmod 700 fileOwner full access only
chmod +x script.shMake script executable

Example:

chmod +x deploy.sh

Ownership:

CommandExplanation
chown user fileChange owner
chown user:group fileChange owner and group
chgrp group fileChange group

The permission structure rwx rwx rwx is shown in the Linux cheatsheet document as the standard format.


Compression & Archiving

tar (most common)

CommandExplanation
tar -cvf archive.tar dirCreate archive
tar -xvf archive.tarExtract archive
tar -czvf archive.tar.gz dirCompress archive
tar -xzvf archive.tar.gzExtract compressed

zip

CommandExplanation
zip archive.zip fileCreate zip
unzip archive.zipExtract zip

rar (optional)

CommandExplanation
rar a archive.rar fileCreate rar
rar x archive.rarExtract rar

Process Management

CommandExplanation
psShow processes
ps auxDetailed process list
topReal-time process monitor
htopAdvanced monitor
kill PIDTerminate process
kill -9 PIDForce kill

Disk & System Monitoring

CommandExplanation
df -hDisk space
du -sh dirDirectory size
free -hMemory usage
uptimeSystem uptime
lsblkShow disks

Networking

CommandExplanation
ping hostTest connectivity
curl urlSend HTTP request
wget urlDownload file
netstat -tulnShow open ports
ss -tulnModern port viewer

Piping & Redirection (Power Feature)

SymbolMeaning
``Pipe output
>Redirect output
>>Append output
2>Redirect error
&>Redirect stdout + stderr

Example:

grep ERROR app.log | sort | uniq > errors.txt

Command Chaining

OperatorMeaning
cmd1 && cmd2Run cmd2 if cmd1 succeeds
`cmd1cmd2`Run cmd2 if cmd1 fails
cmd1 ; cmd2Run both

History & Productivity

CommandExplanation
historyShow command history
!!Repeat last command
!nRun command number
Ctrl + RSearch history
clearClear terminal
man commandShow manual

Introduction to Bash Scripting

Bash scripting is a powerful way to automate tasks on Linux and Unix-like systems using the Bash shell. It involves writing sequences of commands in a plain text file (a script) that can be executed by the Bash shell.

Why Use Bash Scripts?

  • Automation of repetitive tasks
  • System administration and maintenance
  • Complex workflow management
  • Direct OS interaction - commands interact directly with the operating system
  • Versatile and powerful - combine multiple system tools seamlessly

Key Concepts

  • Variables - Store and manipulate data
  • Conditionals - Make decisions in your scripts
  • Loops - Repeat operations efficiently
  • Functions - Create reusable code blocks
  • Script arguments - Accept input parameters
  • File format - Scripts are saved with .sh extension
  • Execution - Make executable with chmod +x and run with ./script.sh

Creating & Running Bash Scripts

Create script

touch script.sh

Shebang (define interpreter)

#!/bin/bash

Make executable

chmod +x script.sh

Run script

./script.sh

Run without executable

bash script.sh

Basic Script Template

#!/bin/bash

set -e
set -u
set -o pipefail

echo "Starting script..."

DATE=$(date)

echo "Current date: $DATE"

Recommended safety options:

OptionMeaning
set -eExit on error
set -uFail if variable undefined
set -o pipefailCatch pipe failures

These make scripts much safer in production.


Variables

Declare variable

NAME="Mahendra"

Use variable

echo "$NAME"

Command output into variable

DATE=$(date)
FILES=$(ls)

Best practices

UPPERCASE for constants
Quote variables "$VAR"
Define variables at top

Script Arguments

Access script parameters

./script.sh file1.txt

Inside script:

$0 → script name
$1 → first argument
$2 → second argument
$# → number of arguments
$@ → all arguments

Example:

FILE=$1
echo "Processing $FILE"

Arrays

Create array

ERRORS=("ERROR" "CRITICAL" "FATAL")

Access elements

${ERRORS[0]}
${ERRORS[@]}

Loop array

for e in "${ERRORS[@]}"
do
echo "$e"
done

Conditionals

Basic syntax

if [ condition ]; then
command
fi

Example

if [ -f file.txt ]; then
echo "File exists"
fi

Common comparisons

OperatorMeaning
-eqequal
-nenot equal
-gtgreater
-ltless
-gegreater or equal
-leless or equal

String comparison

if [ "$VAR" = "value" ]

Loops

For Loop

for file in *.log
do
echo "$file"
done

While Loop

while read line
do
echo "$line"
done < file.txt

Functions

Define function

check_logs() {
echo "Checking logs..."
}

Call function

check_logs

File Tests

TestMeaning
-ffile exists
-ddirectory exists
-sfile not empty
-xexecutable
-rreadable
-wwritable

Example

if [ -d /var/log ]; then
echo "Directory exists"
fi

Logging Output

Print message

echo "Script started"

Write to file

echo "log message" >> log.txt

Redirect errors

command 2> error.log

Redirect all output

command > output.log 2>&1

Debugging Scripts

Enable debug mode

set -x

Disable debug

set +x

Run debug

bash -x script.sh

Scheduling Scripts (Automation)

Cron job format

* * * * * command
│ │ │ │ │
│ │ │ │ └ day of week
│ │ │ └ month
│ │ └ day
│ └ hour
└ minute

Example

0 2 * * * /scripts/backup.sh

Run script every day at 2 AM.


Useful Bash Built-ins

CommandExplanation
readread user input
echoprint output
exitexit script
source filerun script in same shell
export VARenvironment variable

Error Handling Pattern

Production scripts should handle errors.

Example:

if ! command; then
echo "Command failed"
exit 1
fi

Real World Script Example

Log Monitoring Script

#!/bin/bash

LOG_DIR="/var/log"
REPORT="error_report.txt"
ERROR_PATTERNS=("ERROR" "CRITICAL" "FATAL")

echo "Starting log analysis..." > "$REPORT"

LOG_FILES=$(find "$LOG_DIR" -name "*.log")

for FILE in $LOG_FILES
do
echo "Checking $FILE"

for PATTERN in "${ERROR_PATTERNS[@]}"
do
COUNT=$(grep -c "$PATTERN" "$FILE")

if [ "$COUNT" -gt 0 ]; then
echo "$FILE contains $COUNT $PATTERN entries" >> "$REPORT"
fi
done
done

echo "Analysis complete. Report saved to $REPORT"

Mental Model of Bash Automation

Most scripts follow this flow:

INPUT

FIND FILES

FILTER (grep)

PROCESS (loops)

CONDITIONS

REPORT / ACTION