Linux
Your first terminal. Move around, manage files, find anything.
18 levels · 107 lessons · about 3 hours
Linux commands cheat sheet
Every command in the Linux Playground, grouped by level. Practise each one above in the interactive terminal.
Show all 107 commandsHide commands
Level 1: First Steps (Beginner)
Find out where you are and move around the file system.
- Where am I?
pwdThe terminal always works inside one folder, called the current directory. pwd (print working directory) tells you which one.
- List files
lsls lists what is inside the current folder.
- See hidden files & details
ls -laFiles starting with a dot (like .bashrc) are hidden. -l shows details (permissions, owner, size) and -a shows hidden files.
- Change folder
cd projectscd (change directory) moves you into another folder.
- Go back up
cd ..Two dots (..) mean the parent folder - one level up.
Level 2: Files & Folders (Beginner)
Create, read, copy, move and delete files.
- Make a folder
mkdir logsmkdir (make directory) creates a new folder. Add -p to create nested folders in one go.
- Create an empty file
touch app.logtouch creates an empty file, or updates the timestamp if it already exists.
- Read a file
cat notes.txtcat prints a whole file to the screen. Great for short files.
- Copy a file
cp notes.txt notes.bakcp SOURCE DESTINATION copies a file. Use cp -r to copy a whole folder.
- Move or rename
mv notes.bak backup.txtmv moves a file. Moving to a new name in the same folder is how you rename.
- Delete a file
rm backup.txtrm removes a file for good - there is no recycle bin. rm -r removes a folder and everything in it, so double-check first!
Level 3: Search & Read Logs (Intermediate)
Find text in files and watch logs like an on-call engineer.
- Search inside a file
grep ERROR app.loggrep prints only the lines that match a word. It's the #1 tool for reading logs.
- First lines of a file
head -n 5 app.loghead shows the start of a file (10 lines by default). -n sets how many.
- Watch a log live
tail -f app.logtail shows the end of a file. tail -f keeps it open and prints new lines as they arrive.
- Find a file by name
find . -name "*.yaml"find searches folders for files. find PATH -name PATTERN looks by name.
- Chain commands with a pipe
grep ERROR app.log | wc -lThe pipe | sends the output of one command into the next. wc -l counts lines.
Level 4: Permissions & Processes (Intermediate)
Run scripts, check what's running and keep a server healthy.
- Make a script executable
chmod +x deploy.shLinux files have read (r), write (w) and execute (x) permissions. chmod +x lets you run a script.
- Run a script
./deploy.sh./ means 'in this folder'. You need it to run a script that isn't on your PATH.
- See running processes
ps auxps aux lists every running process with its PID (process ID), CPU and memory use.
- Stop a process
kill 812kill sends a signal to a process by its PID. Plain kill asks it to stop nicely; kill -9 forces it.
- Check disk space
df -hdf -h shows free space on each disk in human-readable units (G, M).
- Run as admin
sudo apt install curlsudo runs one command as the administrator (root). apt is the package manager on Ubuntu/Debian.
Level 5: Run a Real Server (Intermediate)
Connect to servers, check ports and manage services like a sysadmin.
- Connect with SSH
ssh ubuntu@10.0.1.25ssh opens a secure terminal on another server, as if you were sitting in front of it. You write it as ssh, then the user name, an @, and the server's address: ssh user@address.
- Is the website up?
curl -I https://akopslabs.comcurl opens a web address from the terminal. Add -I (capital i) to get only the headers: the first line shows the status code, so you see in one second whether the site is up.
- What's listening?
ss -tulpnss lists the ports programs are using. Read the flags one by one: -t TCP, -u UDP, -l only listening, -p show the program, -n numbers instead of names. Together: ss -tulpn.
- Check a service
systemctl status nginxsystemd runs background services. systemctl status shows if a service is running and its latest logs.
- Restart a service
sudo systemctl restart nginxsystemctl restart stops a service and starts it again, for example after you change its config. Changing a service needs admin rights, so put sudo in front.
- Read service logs
journalctl -u nginx -fjournalctl reads the logs of services. -u nginx picks one service (u = unit) and -f follows new lines live, like tail -f. Press Ctrl+C to stop.
Level 6: Text Power Tools (Advanced)
Slice, count and edit text files from the terminal, like log files and configs.
- Cut out one column
cut -d: -f1 /etc/passwdcut picks columns from each line. -d sets the separator and -f the field number. /etc/passwd uses : between fields, and field 1 is the username.
- Count repeated lines
sort ips.txt | uniq -csort puts the same lines next to each other, and uniq -c counts them. Together they answer questions like 'which IP called us most?'.
- Print one field with awk
awk '{print $1}' access.logawk splits each line into fields by spaces. $1 is the first field, $2 the second. Put the awk program in single quotes so the shell leaves $1 alone: awk '{print $1}' file. In a web access log, the first field is the client IP.
- Find and replace in a file
sed -i 's/8080/9090/' app.confsed edits text. s/old/new/ replaces text, and -i saves the change into the file itself. Very common in scripts to change a port or a version.
- Pack a folder
tar -czf backup.tar.gz app/tar bundles files into one archive. -c creates, -z compresses with gzip, -f names the file. Backups and deployments use this all the time.
- Unpack an archive
tar -xzf backup.tar.gz-x extracts. Use the same z and f flags. Add -C folder to extract somewhere else.
Level 7: Users, Network & Scheduling (Advanced)
Create service users, check the network and run jobs on a schedule.
- Create a user
sudo useradd -m deployApps and CI jobs should run as their own user, not root. useradd -m also creates a home folder.
- Add a user to a group
sudo usermod -aG docker deployGroups give permissions. Members of the docker group can run Docker without sudo. -aG appends a group without removing the others.
- Look up a domain
dig akopslabs.comdig asks DNS which IP a name points to. When a site 'does not work', DNS is one of the first things to check.
- Check a server is reachable
ping -c 3 10.0.1.25ping sends small test packets. -c 3 stops after three, so it does not run forever.
- Copy a file to a server
scp backup.tar.gz ubuntu@10.0.1.25:/tmp/scp copies files over SSH. The format is scp file user@host:/path.
- See scheduled jobs
crontab -lcron runs commands on a schedule, like a nightly backup. crontab -l lists your jobs, crontab -e edits them. 0 2 * * * means every day at 02:00.
Level 8: Troubleshoot a Live Server (Advanced)
Find out why a server is slow or broken, the way an on-call engineer does.
- How busy is the server?
uptimeuptime shows how long the server has run and the load average for the last 1, 5 and 15 minutes. Load higher than the number of CPUs means work is queuing up.
- Check memory
free -hfree -h shows used, free and available memory in a readable way. If available is close to 0 and swap is used, the server is out of memory.
- Find what fills the disk
sudo du -sh /var/log/*du -sh shows the size of each item. Logs in /var/log are the most common reason a disk fills up.
- Who is using this port?
sudo lsof -i :8080lsof -i :PORT shows which process has the port open. Use it when an app fails with 'address already in use'.
- Read only the errors
journalctl -p err -bjournalctl -p err shows only error messages. -b limits it to the current boot. A fast way to see what broke.
- Live view of processes
toptop shows processes live, sorted by CPU. Press M to sort by memory and q to quit. htop is a friendlier version.
Level 9: Users & Permissions Deep Dive (Advanced)
Read and set permissions and owners, and run commands as other users, like on a real production server.
- Read the permissions
ls -l app.confls -l shows who may do what. -rw-r--r-- reads as three groups of three: the owner can read and write (rw-), the group can read (r--), everyone else can read (r--). Then come the owner and the group names.
- Set permissions with numbers
chmod 640 app.confEach permission has a number: r = 4, w = 2, x = 1. Add them up for owner, group and others. 6 = 4+2 (rw), 4 = r, 0 = nothing. So 640 means: owner reads and writes, group reads, others get nothing. Perfect for a config file with secrets.
- Change the owner
sudo chown www-data:www-data /var/www/html/index.htmlchown changes who owns a file: chown user:group file. Web servers like nginx run as the www-data user, so the files they serve should belong to www-data. Changing an owner needs sudo.
- Check a user's groups
id deployid shows a user's number (uid) and every group they are in. Groups give extra rights, for example the docker group can run docker without sudo.
- Run a command as another user
sudo -u deploy whoamisudo -u runs one command as a different user. It's the safe way to test what a service account can do, without logging in as it.
- Find risky files
find /var/www -type f -perm -o+wA file anyone can write to (world-writable) is a security hole: an attacker could change it. find -perm -o+w finds them. -type f looks at files only.
Level 10: Shell Scripting Basics (Advanced)
Use variables, exit codes, arguments and loops: the building blocks of every script.
- Set a variable
APP=webA variable stores a value for later. No spaces around =. By convention, names are in capitals.
- Use the variable
echo "Deploying $APP"Put $ in front of a variable's name to use its value. Double quotes keep the text together.
- Check the exit code
echo $?Every command returns an exit code: 0 means success, anything else means failure. $? holds the last one. Scripts and CI pipelines decide what to do next from it.
- Pass an argument
./deploy.sh stagingScripts read arguments as $1, $2... so one script can deploy to any environment.
- Loop over servers
for s in web api db; do echo $s; doneA for loop repeats a command for each item. This is how you run the same check on many servers.
- Run only if it worked
test -f app.conf && echo found&& runs the next command only if the first one succeeded. test -f checks that a file exists.
Level 11: Environment & PATH (Expert)
Control the settings every program reads: environment variables, PATH and aliases.
- See the environment
envEnvironment variables are settings passed to every program you start, like HOME, USER and PATH.
- Export a variable
export DB_HOST=10.0.1.5export makes a variable visible to programs you start from this shell. Apps read DB_HOST, API keys and ports this way (the twelve-factor way).
- Where are commands found?
echo $PATHPATH is a list of folders the shell searches, in order, when you type a command.
- Which program runs?
which python3which shows the exact file that runs for a command. Handy when two versions are installed.
- Make a shortcut
alias ll='ls -la'An alias is a short name for a longer command. Put aliases in ~/.bashrc to keep them.
- Reload your settings
source ~/.bashrcAfter editing ~/.bashrc, source re-reads it in the current shell, so you don't need to log in again.
Level 12: Disks & Storage (Expert)
Add a new disk to a server: find it, format it, mount it and keep it mounted after reboot.
- List the disks
lsblklsblk lists block devices: disks and their partitions. A new cloud volume shows up here with no mount point.
- Format the new disk
sudo mkfs.ext4 /dev/xvdfmkfs creates a file system on a disk. ext4 is the common Linux choice. Careful: this erases the disk.
- Make a mount point
sudo mkdir /dataA mount point is just an empty folder where the disk will appear.
- Mount the disk
sudo mount /dev/xvdf /datamount attaches the disk to the folder. Everything written to /data now goes to the new disk.
- Find the disk's UUID
sudo blkid /dev/xvdfDevice names can change after a reboot. The UUID never does, so use it in /etc/fstab.
- Test fstab before rebooting
sudo mount -aLines in /etc/fstab mount disks at boot. mount -a mounts everything in it now, so a typo is found before it stops the server booting.
Level 13: Packages & Services (Expert)
Install software, keep it updated and make services start on boot.
- Refresh the package list
sudo apt updateapt update downloads the latest list of available packages. Always run it before installing.
- Install the updates
sudo apt upgrade -yapt upgrade installs newer versions of what you have, including security fixes. -y answers yes.
- Start on boot
sudo systemctl enable --now nginxenable makes systemd start the service every time the server boots. --now also starts it right away.
- Is it running?
systemctl is-active nginxis-active answers with one word, which makes it perfect for scripts and health checks.
- List running services
systemctl list-units --type=service --state=runningSee every service that is running right now.
- Reload unit files
sudo systemctl daemon-reloadAfter you create or edit a .service file, systemd must re-read it. Forgetting this is a classic mistake.
Level 14: Networking Deep Dive (Expert)
Find IPs, routes and DNS settings, and prove whether a port is reachable.
- Show IP addresses
ip aip a lists network interfaces and their IP addresses. eth0 or ens5 is usually the main one.
- Show the routes
ip routeThe routing table decides where traffic goes. The default route points to the gateway that leads to the internet.
- Which DNS server?
cat /etc/resolv.conf/etc/resolv.conf lists the DNS servers the machine asks to turn names into IPs.
- Is the database port open?
nc -zv 10.0.1.40 5432nc -zv tries to connect to a port without sending data. It's the fastest way to prove a firewall or security group allows it.
- See every hop
traceroute akopslabs.comtraceroute shows each router between you and a host, so you can see where a connection stops.
- Debug an HTTP call
curl -v http://localhost:8080/healthcurl -v shows the whole conversation: DNS, the TCP connection, TLS, request headers and response headers.
Level 15: Firewall & SSH Security (Expert)
Lock a server down: a firewall, SSH keys and a safe SSH config.
- Check the firewall
sudo ufw statusufw (uncomplicated firewall) is Ubuntu's simple firewall.
- Allow SSH first
sudo ufw allow 22/tcpAlways allow SSH before you turn the firewall on, or you lock yourself out of the server.
- Allow web traffic
sudo ufw allow 443/tcpOpen only the ports the server really needs.
- Turn the firewall on
sudo ufw enableNow everything not allowed is blocked.
- Make an SSH key
ssh-keygen -t ed25519 -C "you@akopslabs.com"SSH keys are safer than passwords. ed25519 is the modern, recommended type. -C adds a label.
- Copy the key to a server
ssh-copy-id ubuntu@10.0.1.25ssh-copy-id adds your public key to the server's authorized_keys, so you log in without a password.
- Test the SSH config
sudo sshd -tAfter setting PasswordAuthentication no in /etc/ssh/sshd_config, test it before restarting, or a typo can lock everyone out.
Level 16: Logs & Rotation (Expert)
Search system logs by time and stop logs from filling the disk.
- Read the system log
sudo tail -n 20 /var/log/syslogOn Ubuntu, /var/log/syslog collects messages from most services.
- Logs from the last hour
journalctl --since "1 hour ago"--since filters journal logs by time. Perfect for "what happened during the outage?".
- How big are the logs?
journalctl --disk-usageThe journal can grow to gigabytes.
- Shrink the journal
sudo journalctl --vacuum-size=500M--vacuum-size deletes the oldest journal files until the total is below the size you give.
- Test log rotation
sudo logrotate -d /etc/logrotate.d/nginxlogrotate compresses and deletes old log files on a schedule. -d is a dry run: it shows what it would do.
- Search compressed logs
zgrep ERROR app.log.2.gzRotated logs are gzipped. zgrep searches them without unpacking.
Level 17: Performance Tuning (Expert)
Find what is slowing a server down: CPU, memory, disk or open files.
- How many CPUs?
nprocnproc prints the number of CPU cores. A load average above this number means work is waiting.
- Watch the system
vmstat 1 5vmstat shows CPU, memory, swap and I/O every second. High 'wa' means the CPU is waiting for the disk.
- Check the disks
iostat -x 1 3iostat -x shows how busy each disk is. %util near 100 means the disk is the bottleneck.
- Top memory users
ps aux --sort=-%mem | head -n 5Sort processes by memory to find the one eating RAM.
- Lower a process's priority
sudo renice -n 10 -p 2231renice changes a running process's priority. 10 means 'be nice': let other processes go first.
- Open file limit
ulimit -nBusy servers hit the 'too many open files' error. ulimit -n shows the limit for your shell.
Level 18: Bash Automation Pro (Expert)
Write scripts that are safe, debuggable and can run on many servers.
- Check a script for typos
bash -n deploy.shbash -n reads the script and reports syntax errors without running anything.
- Trace a script
bash -x deploy.shbash -x prints every command before it runs, with variables filled in. The first thing to do when a script misbehaves.
- Fail fast
set -euo pipefailset -euo pipefail at the top of a script stops it on the first error, on unset variables and on failures inside pipes. Every production script should have it.
- Run on many servers
cat servers.txt | xargs -I{} ping -c 1 {}xargs turns lines of input into arguments. -I{} puts each line where {} is.
- Keep running after logout
nohup ./backup.sh &nohup plus & runs a long job in the background that keeps going after you close SSH.
- Watch a value change
watch -n 5 df -hwatch reruns a command every few seconds. Great for watching disk space during a cleanup.