Skip to main content
CodingMarble

Interview questions and cheat sheets

Linux Commands Cheat Sheet for Developers and Servers

This cheat sheet groups the Linux commands a developer needs on a server by the job they do: moving around, changing permissions, searching, reading logs, managing processes, checking disk and network, and connecting over SSH. It ends with the commands that destroy data and the habits that keep you safe.

By CodingMarble · Published · 4 min read

Close-up of a computer keyboard
Photo: Christian Wiediger on Unsplash

Permissions and ownership

Every file has three permission groups: the owner, the group and everyone else. Each group can have read (r), write (w) and execute (x). The numeric form adds a value for each: read is 4, write is 2 and execute is 1, so each digit is the sum for one group. Three digits give owner, group and others in that order.

  • 7 = 4+2+1, so rwx: read, write and execute.
  • 6 = 4+2, so rw-: read and write, a typical file.
  • 5 = 4+1, so r-x: read and execute, with no writing.
  • 4 = r--: read only. 0 = ---: no access.
  • 755 means rwxr-xr-x: the owner can do everything, others can read and run. Typical for directories and scripts.
  • 644 means rw-r--r--: the owner can edit, others only read. Typical for ordinary files.
  • 600 means rw-------: owner only, the right choice for private keys and secret config.
Shell· Change and inspect permissions
ls -l deploy.sh              # -rw-r--r-- 1 user group ... deploy.sh
chmod 755 deploy.sh          # numeric form
chmod u+x deploy.sh          # symbolic: add execute for the owner
chmod go-w shared.txt        # remove write for group and others
chown deploy:deploy app.log  # change owner and group (needs sudo for other users)
sudo chown -R www-data:www-data /var/www/site

Practical tip: when a web server cannot read your files, work out which user it runs as, then check that user can traverse every directory in the path (the x bit on each folder) and read the file. Permission errors are usually on a parent directory, not on the file itself.

Searching files and reading logs

grep searches the contents of files, while find searches for files by name, type, size or age. They combine well: find locates candidates and grep looks inside them. Quote patterns so the shell does not expand them before the command sees them.

Shell· grep and find
grep -rn "TODO" src/             # recursive, with line numbers
grep -i "error" app.log          # ignore case
grep -v "healthcheck" access.log # lines that do NOT match
grep -c "500" access.log         # count matching lines
find . -name "*.log"             # by name
find . -type f -mtime -1         # files changed in the last day
find . -type f -size +100M       # files larger than 100 megabytes

For logs, tail -f follows a file as new lines arrive, which is the quickest way to watch a request fail in real time. On systems using systemd, services often log to the journal instead of a file, and journalctl reads it. Press Ctrl+C to stop following.

Shell· Watching logs
tail -n 100 app.log                    # last 100 lines
tail -f /var/log/nginx/error.log       # follow new lines
journalctl -u nginx -f                 # follow one service's journal
journalctl -u nginx --since "1 hour ago"
journalctl -p err -b                   # errors since the last boot

Processes, disk and memory

A process is a running program with a numeric ID, the PID. ps lists a snapshot, top shows a live view, and kill sends a signal to a PID. A plain kill sends SIGTERM, which asks the program to shut down cleanly. kill -9 sends SIGKILL, which the program cannot catch or clean up after, so use it only when the polite request is ignored.

Shell· Find and stop a process
ps aux | grep node       # list processes, filter for node
pgrep -f "server.js"     # print matching PIDs only
top                      # live view (q quits)
kill 4321                # ask PID 4321 to exit
kill -9 4321             # force it, last resort
pkill -f "server.js"     # signal by matching the command line

When a server misbehaves, the cause is often a full disk or exhausted memory. df reports free space per filesystem, du reports how much a folder uses, and free shows memory. The -h flag prints sizes in readable units.

Shell· Disk and memory
df -h                              # space per mounted filesystem
du -sh /var/log                    # total size of one folder
du -h --max-depth=1 /var | sort -h # biggest subfolders last
free -h                            # memory and swap

Networking, SSH and file transfer

curl makes HTTP requests from the terminal, which separates a server problem from a browser problem. ss lists sockets and shows which process listens on which port. ping tests basic reachability, though many hosts block it on purpose, so a failed ping does not prove a host is down. dig queries DNS records.

Shell· Network checks
curl -I https://example.com                       # response headers only
curl -s -o /dev/null -w "%{http_code}\n" https://example.com   # status code only
ss -tulpn                                          # listening ports and owning processes
ping -c 4 example.com                              # four probes then stop
dig example.com +short                             # A record
dig MX example.com +short                          # mail servers

SSH opens an encrypted shell on a remote machine, and scp copies files over the same connection. Key-based login is safer than passwords. Generate a key pair once, place the public key on the server, and keep the private key private with permissions 600, since SSH refuses keys that other users can read.

Shell· SSH and scp
ssh-keygen -t ed25519 -C "laptop"             # create a key pair
ssh user@203.0.113.10                          # connect
ssh -i ~/.ssh/id_ed25519 user@203.0.113.10     # choose a key
scp backup.zip user@203.0.113.10:/home/user/   # upload a file
scp -r user@203.0.113.10:/var/www/site ./site  # download a folder

Package managers, pipes and redirects

Each distribution family has its own package manager, but the verbs are alike: refresh the index, install, remove and search. Debian and Ubuntu use apt, Fedora and Red Hat family systems use dnf, Alpine uses apk and Arch uses pacman. Installing needs elevated rights, so commands are prefixed with sudo. Confirm the exact syntax in your distribution's documentation.

Shell· The same job on two families
sudo apt update && sudo apt install nginx     # Debian or Ubuntu
sudo dnf install nginx                         # Fedora or RHEL family

A pipe, written |, feeds the output of one command into the next, so small tools combine into larger ones. Redirects send output to files: > replaces a file's contents, >> appends, and 2> captures error output, which travels on a separate stream from normal output. The example counts the most frequent client addresses in an access log whose first field is the address.

Shell· Pipes and redirects
ls | wc -l                                    # count entries
cut -d' ' -f1 access.log | sort | uniq -c | sort -rn | head
echo "deployed" >> deploy.log                  # append a line
./build.sh > build.log 2>&1                    # both streams to one file
./build.sh 2>/dev/null                         # discard errors
dmesg | tee kernel.txt | less                  # save a copy while viewing

Dangerous commands and safe habits

Warning: the commands below can erase data or open security holes with no confirmation and no undo. Read each one twice, and never paste a command you do not understand into a server terminal, especially as root.

  • rm -rf deletes files and whole folders recursively without asking, and there is no trash. A stray space or an empty variable can point it at the wrong place, as in rm -rf $DIR/ with DIR unset. Run ls with the same path first, use rm -ri when unsure, and never run it as root without checking pwd.
  • chmod -R 777 makes everything readable, writable and executable by every user, which lets any compromised process or account alter your code. It is a common but wrong fix for permission errors. Find the actual owner and use 755 for directories and 644 for files instead.
  • dd copies raw bytes between devices, and swapping the input and output targets overwrites a disk. Confirm device names with lsblk before every run and double-check the of= target.
  • A redirect with > silently truncates an existing file, so echo x > important.conf destroys what was there. Use >> to append, or set noclobber in your shell.
  • Piping a downloaded script straight into a root shell, as in curl | sudo bash, runs code you have not read. Download it, read it, then run it.
Shell· Safer habits in practice
ls /var/www/old-site           # look before you delete
rm -ri /var/www/old-site       # confirm each deletion
cp -a /etc/nginx /etc/nginx.bak  # back up before editing config
sudo chmod 640 .env            # tighten, do not loosen
lsblk                          # check the device before using dd

Need this built properly for your business?

CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.