Helper-KitCheatsheets

Bash Cheatsheet

Linux and Bash terminal commands for files, search, pipes, permissions, processes, networking and scripts. Search, copy or print.

Bash Cheatsheet · Helper-Kit

Works in Bash on Linux and macOS, and in WSL or Git Bash on Windows. Some options differ slightly on macOS.

62 entries

Navigate

Where am I?

Print the current folder.

pwd

List files

Long format with hidden files, and human-readable sizes.

ls
ls -la
ls -lh

Change folder

Go to a path, up one level, home, or back to the previous folder.

cd /path/to/folder
cd ..
cd ~
cd -

Show a folder tree

Two levels deep (install the tree package if it’s missing).

tree -L 2

Files & folders

Create a folder

-p creates parent folders as needed and does not fail if it exists.

mkdir new-folder
mkdir -p path/to/folder

Create an empty file

Creates the file, or updates its modified time if it exists.

touch notes.txt

Copy

Copy a file, or a folder with everything in it.

cp file.txt copy.txt
cp -r folder/ backup/

Move or rename

Rename a file, or move it into another folder.

mv old.txt new.txt
mv file.txt /path/to/folder/

Delete a file

Careful

There is no recycle bin: deleted files are gone.

rm file.txt
rm -i file.txt

-i asks before each delete.

Delete a folder

Careful

rmdir only removes empty folders. rm -r removes a folder and everything in it.

rmdir empty-folder
rm -r folder/

Double-check the path before running rm -rf. It never asks.

Create a link

A symbolic link (shortcut) pointing to another file or folder.

ln -s /path/to/target link-name

View files

Print a file

Show the whole file at once.

cat file.txt

Scroll through a file

Space for next page, / to search, q to quit.

less file.txt

First or last lines

The first 20 lines, or the last 20.

head -n 20 file.txt
tail -n 20 file.txt

Follow a log file

Keep showing new lines as they are written. Ctrl+C to stop.

tail -f /var/log/syslog

Count lines, words, bytes

-l counts lines only.

wc file.txt
wc -l file.txt

Search inside files

Case-insensitive, recursive, with line numbers.

grep "error" app.log
grep -rin "todo" src/

Find files by name

Search the current folder and below.

find . -name "*.log"
find . -type d -name "node_modules"

Find large or recent files

Files over 100 MB, or changed in the last 7 days.

find . -type f -size +100M
find . -type f -mtime -7

Replace text with sed

Print with replacements, or edit the file in place.

sed 's/old/new/g' file.txt
sed -i 's/old/new/g' file.txt

On macOS use sed -i '' for in-place edits.

Print columns with awk

Print the 1st and 3rd column of each line.

awk '{print $1, $3}' file.txt
awk -F, '{print $2}' data.csv

Sort and remove duplicates

uniq only removes duplicates that are next to each other, so sort first.

sort file.txt | uniq
sort -n numbers.txt
sort file.txt | uniq -c | sort -rn

Cut out a column

The 2nd comma-separated field of each line.

cut -d, -f2 data.csv

Pipes & redirection

Pipe

Send one command’s output into the next.

ls | wc -l
ps aux | grep node

Write output to a file

> replaces the file, >> adds to the end.

command > output.txt
command >> output.txt

> overwrites the file without asking.

Redirect errors

Send errors to a file, both output and errors to one file, or discard errors.

command 2> errors.txt
command > all.txt 2>&1
command 2>/dev/null

Show and save output

Print output and write it to a file at the same time.

command | tee output.txt

Run the next command only if…

&& runs if the first succeeded; || runs if it failed; ; always runs.

npm test && npm run build
mkdir out || echo "failed"
cd /tmp; ls

Run a command on each result

Careful

Pass each found file to another command.

find . -name "*.tmp" -print0 | xargs -0 rm

Permissions

Make a script executable

Then run it with ./script.sh

chmod +x script.sh

Set permissions with numbers

7 = read+write+execute, 6 = read+write, 5 = read+execute, 4 = read. Order: owner, group, others.

chmod 755 script.sh
chmod 644 file.txt
chmod 600 ~/.ssh/id_ed25519

Change owner

Change the owner, or the owner and group, of a file or folder.

sudo chown user file.txt
sudo chown -R user:group folder/

Run as administrator

Run one command as root.

sudo command

Who am I?

Your user name, and your user and group IDs.

whoami
id

Processes

List processes

Every running process, or a live view sorted by CPU.

ps aux
top

htop is a friendlier version of top, if installed.

Stop a process

Careful

Ask nicely first; -9 forces it to stop immediately.

kill <PID>
kill -9 <PID>
pkill -f "node server.js"

-9 gives the program no chance to save its work.

Run in the background

Start a job in the background, list jobs, bring one back.

long-command &
jobs
fg %1

Keep running after logout

Output goes to nohup.out.

nohup long-command &

Which program will run?

Show the full path of a command.

which node
type ls

System & disk

Disk space

Free space per drive, and the size of a folder.

df -h
du -sh folder/
du -sh * | sort -h

Memory

Used and free memory (Linux).

free -h

System info

Kernel version and how long the system has been running.

uname -a
uptime

Environment variables

Show all, show one, or set one for this session.

env
echo $PATH
export API_URL="https://example.com"

Command history

Show past commands; !! repeats the last one; Ctrl+R searches.

history
!!
sudo !!

Network

Download a file

Save a URL to a file with curl or wget.

curl -O https://example.com/file.zip
wget https://example.com/file.zip

Call an API

GET with headers shown, and a JSON POST.

curl -i https://api.example.com/items
curl -X POST -H "Content-Type: application/json" -d '{"name":"test"}' https://api.example.com/items

Connect to a server

Log in over SSH, optionally with a key or another port.

ssh user@host
ssh -i ~/.ssh/id_ed25519 -p 2222 user@host

Copy files to or from a server

scp for simple copies, rsync to sync only what changed.

scp file.txt user@host:/path/
rsync -avz folder/ user@host:/path/folder/

Check a connection

Ping a host 4 times, and show listening ports (Linux).

ping -c 4 example.com
ss -tulpn

Archives

Create a .tar.gz

c = create, z = gzip, f = file name.

tar -czf archive.tar.gz folder/

Extract a .tar.gz

Extract here, or into another folder.

tar -xzf archive.tar.gz
tar -xzf archive.tar.gz -C /path/to/folder

List what’s inside

Without extracting.

tar -tzf archive.tar.gz

Zip and unzip

Create or extract a .zip file.

zip -r archive.zip folder/
unzip archive.zip

Scripting

Script template

Stop on errors, on unset variables, and on failures inside pipes.

#!/usr/bin/env bash
set -euo pipefail

echo "Hello"

Variables

No spaces around =. Quote variables when you use them.

name="World"
echo "Hello, $name"
echo "Saved to ${name}.txt"

Command output in a variable

Store the result of a command.

today=$(date +%Y-%m-%d)
files=$(ls | wc -l)

Script arguments

$1 is the first argument, $# the number of arguments, "$@" all of them.

echo "First: $1"
echo "Count: $#"
for arg in "$@"; do echo "$arg"; done

If

Check whether a file exists, or compare text.

if [[ -f "config.json" ]]; then
  echo "Found"
elif [[ "$env" == "prod" ]]; then
  echo "Production"
else
  echo "Missing"
fi

For loop

Loop over files, or over a range of numbers.

for f in *.txt; do
  echo "$f"
done

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

While loop over lines

Read a file one line at a time.

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

Function

Define and call a function with an argument.

greet() {
  echo "Hello, $1"
}
greet "World"

Exit code

0 means success; anything else means failure.

echo $?
exit 1

💡 Search matches titles, descriptions and the commands themselves. Copy puts the exact text on your clipboard; Print gives a clean sheet without menus or buttons. Searching happens in your browser; nothing is sent anywhere.

About This Cheatsheet

Bash is the command-line shell on most Linux servers and the default on many systems, and macOS's zsh accepts nearly all of the same commands. This cheatsheet covers the everyday commands for moving around, managing files, viewing and searching text, pipes and redirection, permissions, processes, disk space, networking, archives and writing scripts. Each card explains what the command does in plain words, and the commands that delete files or stop programs are marked Careful. Notes point out the few places where macOS behaves differently from Linux. On Windows you can run these commands in WSL (Windows Subsystem for Linux) or Git Bash.

Quick Tips

  • Press Tab to complete file and command names, and Ctrl+R to search your command history.
  • Run ls on a path before rm -r on it, so you know exactly what will be deleted.
  • Quote variables ("$file") so names with spaces don't break your commands.
  • Start scripts with set -euo pipefail so they stop at the first error.
  • Add --help to most commands, or run man <command>, to see all their options.

Frequently Asked Questions

What is the difference between Bash and the terminal?

The terminal is the window you type in. Bash is the program inside it that reads and runs your commands. Other shells include zsh (the macOS default) and PowerShell.

How do I run a script?

Make it executable with chmod +x script.sh, then run ./script.sh. You can also run bash script.sh without changing permissions.

What does 2>&1 mean?

It sends errors (stream 2) to the same place as normal output (stream 1), so command > log.txt 2>&1 saves both to the file.

Can I undo rm?

No. rm deletes files immediately without a recycle bin. Use rm -i to be asked before each file, and double-check paths before using rm -r.

Was this tool helpful?

More in this category