back

Bash cheatsheet

Fork, clone, or contribute via the Github repo to keep it evolving with your needs.

Let’s dive in-

Introduction to Bash

Bash (Bourne Again SHell) is a command interpreter for Linux/Unix. You use Bash to:

  • Execute commands
  • Automate tasks
  • Write scripts
  • Manage processes
  • Work with the system and network

Check version:

bash --version

Run Bash explicitly:

/bin/bash

Basic Commands

whoami        # current user
pwd           # print working directory
clear         # clear terminal
history       # command history
date          # current date/time
uptime        # system load & uptime
uname -a      # system info

Filesystem Navigation

ls            # list
ls -l         # long view
ls -a         # show hidden files
cd /path      # change directory
cd ~          # home
cd ..         # go up one level
cd -          # previous directory

File & Directory Operations

Create

touch file.txt
mkdir folder
mkdir -p nested/folder/structure

Copy / Move / Delete

cp src dst
cp -r dir1 dir2
mv old new
rm file
rm -r folder
rm -rf folder      # beware: force delete

File Info

stat file.txt
du -sh folder
df -h

Viewing & Editing Content

cat file
tac file
head -n 20 file
tail -f logfile
nano file
vim file

Search inside files:

grep "text" file
grep -ri "keyword" .

Permissions & Ownership

View

ls -l

Change Permissions

chmod 755 script.sh
chmod u+x file
chmod g-w file

Change Ownership

sudo chown user:group file

Legend:

  • r = read
  • w = write
  • x = execute

Environment Variables

View:

printenv
echo $PATH

Set:

export VAR=value

Permanent (in ~/.bashrc):

export PATH="$PATH:/custom/bin"

Unset:

unset VAR

Command Line Operators

Redirection

>   # overwrite
>>  # append
<   # input file

Examples:

ls > out.txt
echo "test" >> log.txt

Logical Operators

cmd1 && cmd2   # run cmd2 only if cmd1 succeeds
cmd1 || cmd2   # run cmd2 only if cmd1 fails
cmd1 ; cmd2    # run sequentially

Pipelines

cmd1 | cmd2 | cmd3

Example:

ps aux | grep bash | wc -l

Process Management

ps aux
top
htop
kill PID
kill -9 PID      # force kill
jobs
fg %1
bg %1

Run in background:

command &

Run immune to hangup:

nohup script.sh &

Networking Essentials

ip a
ip r
ping host
curl http://site.com
wget file
traceroute host
netstat -tulnp
ss -tulnp

DNS lookup:

dig domain.com
host domain.com

Package Management

Debian/Ubuntu

sudo apt update
sudo apt install pkg
sudo apt remove pkg

RedHat/CentOS

sudo yum install pkg
sudo dnf install pkg

Bash Scripting Essentials

Every script starts with a shebang:

#!/bin/bash

Make script executable:

chmod +x script.sh

Run it:

./script.sh

Variables

name="Sir"
echo "$name"

Constants:

readonly PI=3.14

Arithmetic:

echo $((5 + 3))
let x=5+2

User Input

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

Silent input:

read -sp "Password: " pass

Conditions & Comparisons

If / Else

if [ $a -gt 10 ]; then
    echo "big"
elif [ $a -eq 10 ]; then
    echo "equal"
else
    echo "small"
fi

File tests

[ -f file ]     # regular file
[ -d dir ]      # directory
[ -r file ]     # readable
[ -w file ]     # writable
[ -x file ]     # executable

String tests

[ "$a" = "$b" ]
[ -z "$a" ]      # empty

Loops

For

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

While

while true; do
    echo "looping"
    sleep 1
done

Until

until [ "$x" -eq 5 ]; do
    echo "$x"
done

Functions

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

greet "Sir"

Return values:

return 5

Arrays

arr=(a b c)
echo ${arr[0]}
echo ${arr[@]}
echo ${#arr[@]}

String Operations

str="abcdef"
echo ${str:2:3}          # substring
echo ${str#abc}          # remove prefix
echo ${str%def}          # remove suffix
echo ${str/abc/xyz}      # replace once

File Operations in Scripts

Read file line-by-line

while IFS= read -r line; do
    echo "$line"
done < file.txt

Check if file exists

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

Error Handling

Exit code:

echo $?

Strict mode (recommended):

set -euo pipefail

Try/catch-like:

command || { echo "failed"; exit 1; }

Advanced Bash Concepts

Command substitution

files=$(ls)

Here-doc

cat <<EOF
This is
a multi-line
string
EOF

Cron jobs

crontab -e

Aliases

alias ll="ls -al"

Traps

trap "echo Ctrl-C pressed" SIGINT

Security-Focused Bash Tips

Safe file deletion (shredding)

shred -u file.txt

Check open ports

ss -tulnp

Find world-writable files

find / -type f -perm -002 2>/dev/null

Hash a file (integrity)

sha256sum file.iso

Compare directories

diff -qr dirA dirB

Appendix: Common Bash One-Liners

Find big files

find / -type f -size +100M 2>/dev/null

Count files

ls -1 | wc -l

Kill process by name

pkill firefox

Monitor log updates

tail -f /var/log/syslog

Quick web request

curl -I https://example.com

Extract only IP addresses

grep -oE "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+"