PrepStack › DevOps & Cloud › Linux & Shell

Linux & Shell interview cheat sheet

Filesystem, permissions, processes, signals, pipes, text tools, networking and troubleshooting

Linux questions show up in DevOps, SRE, backend and even frontend interviews. Interviewers check that you understand how the system works (inodes, permissions, processes, signals, file descriptors) and that you can debug a real box with the right commands: disk full, high CPU, port already in use, a slow server. Read the 15-minute revision first, then practise the troubleshooting scenarios out loud as if you were sharing your terminal.

15-minute revision

  1. Kernel manages hardware, memory, processes and syscalls. The shell (bash, zsh) is a user program that reads commands. A distro is kernel + userland + package manager + defaults (Ubuntu, RHEL, Debian, Alpine).
  2. Boot: firmware (BIOS/UEFI) → bootloader (GRUB) → kernel + initramfs → PID 1 (systemd) → targets and services.
  3. Everything is a file: regular files, directories, devices (/dev/sda), pipes, sockets and kernel views (/proc, /sys) all use the same open/read/write API.
  4. An inode holds metadata and block pointers, not the name. A hard link is another name for the same inode; a symlink is a small file that stores a path and can dangle.
  5. Permissions: r=4 w=2 x=1 for user/group/other. chmod 755 = rwxr-xr-x. New file mode = 666 & ~umask (dirs 777 & ~umask), so umask 022 gives 644/755.
  6. setuid runs a binary as its owner (passwd), setgid on a dir makes new files inherit the group, the sticky bit on /tmp lets only owners delete their files.
  7. Every process has a PID and PPID. New processes are made by fork() (copy) then exec() (replace image). Zombie = exited but not reaped by parent; orphan = parent died, adopted by PID 1 / a subreaper.
  8. SIGTERM (15) asks politely and can be trapped; SIGKILL (9) and SIGSTOP cannot be caught. SIGHUP (1) = terminal closed, often reused to reload config. kill sends SIGTERM by default.
  9. fd 0 = stdin, 1 = stdout, 2 = stderr. cmd > f 2>&1 sends both to f; 2>&1 > f does not (order matters). >/dev/null discards.
  10. A pipe connects stdout of one process to stdin of the next; all stages run concurrently. $? is the last command's exit code; set -o pipefail makes a pipeline fail if any stage fails.
  11. Text toolkit: grep (filter lines), sed (edit stream), awk (columns and logic), cut, sort | uniq -c | sort -rn (top-N), wc -l, xargs (args from stdin), find, tail -f.
  12. systemctl start|stop|restart|enable|status <unit>; logs with journalctl -u <unit> -f. enable = start at boot; start = start now.
  13. Load average is the 1/5/15-minute average of runnable + uninterruptible (D state) tasks. Compare it to the CPU count; on Linux high load can mean I/O wait, not just CPU.
  14. free -h: look at available, not free. Linux uses spare RAM for page cache. When memory runs out the OOM killer kills the process with the highest oom_score.
  15. Disk full? df -h (space) and df -i (inodes), then du -sh * | sort -h. Space not freed after rm? A process still holds the deleted file open: lsof +L1.
  16. Port in use? ss -ltnp | grep :8080 or lsof -i :8080. Scripts should start with #!/usr/bin/env bash and set -euo pipefail, and always quote variables: "$var".

Foundations: kernel, boot & filesystem

Kernel vs shell vs distro (and package managers)

The kernel runs the hardware, the shell is just a program you type into, and a distro packages both with tools and a package manager.

  • The kernel is the core of the OS. It runs in privileged mode and manages CPU scheduling, memory, devices, filesystems and networking. Programs reach it through system calls (open, read, fork, execve).
  • User space is everything else: the shell, coreutils (ls, cp), daemons and your apps. A bug in user space crashes one process; a kernel bug can crash the machine.
  • The shell is a command interpreter: it parses your line, expands variables and globs, sets up redirections and pipes, and then forks and execs programs. bash, zsh, sh (dash on Debian/Ubuntu) and fish are shells.
  • A distribution bundles the Linux kernel, GNU or BusyBox userland, an init system, a package manager and default configs. Examples: Debian/Ubuntu (apt, .deb), RHEL/Fedora/Rocky (dnf, .rpm), Alpine (apk, musl libc, popular in containers).
  • Package managers resolve dependencies, verify signatures and track installed files. Low-level tools (dpkg, rpm) install a single file without dependency resolution.

Interview questions

  • What is the difference between the kernel and the shell?
  • What does a system call do, and how can you see them?
  • Why is cd a shell builtin and not a program?

Boot process: firmware → GRUB → kernel → systemd

Firmware finds a bootloader, the bootloader loads the kernel and initramfs, the kernel mounts root and starts PID 1, and systemd brings up services.

  • BIOS (legacy) runs POST and loads the first 512-byte sector (MBR). UEFI reads a FAT-formatted EFI System Partition and runs a .efi bootloader directly; it supports GPT disks over 2 TB and Secure Boot.
  • The bootloader (GRUB2, systemd-boot) shows a menu, loads the kernel image (vmlinuz) and the initramfs into memory and passes the kernel command line (root=, quiet, ...).
  • The kernel decompresses itself, initialises CPU, memory and drivers, and unpacks the initramfs: a tiny root filesystem with the drivers and tools needed to find the real root (LVM, RAID, encryption).
  • The real root filesystem is mounted and the kernel starts PID 1: /sbin/init, which is systemd on almost all modern distros (SysV init and OpenRC still exist).
  • systemd reads unit files and starts services in parallel to reach the default target (multi-user.target for servers, graphical.target for desktops). Targets replaced the old runlevels.

Interview questions

  • Walk me through the Linux boot process.
  • Difference between BIOS and UEFI?
  • What is PID 1 and why is it special?

Filesystem hierarchy & “everything is a file”

One tree rooted at /; each top-level directory has a job, and devices, processes and kernel settings appear as files.

  • There are no drive letters. Every disk is mounted somewhere in a single tree starting at /.
  • Everything is a file: regular files, directories, block and character devices (/dev/sda, /dev/null), named pipes, sockets and symlinks. The same open/read/write/close calls work on all of them.
  • /proc and /sys are virtual filesystems created by the kernel in memory. /proc/<pid>/ shows each process; /proc/meminfo, /proc/cpuinfo show system state; /sys exposes devices and drivers.
  • /tmp is for short-lived files (often a tmpfs in RAM, cleared on reboot). /var holds data that changes: logs, caches, spools, databases.
  • File types appear as the first character of ls -l: - file, d dir, l symlink, c char device, b block device, p pipe, s socket.

Interview questions

  • What does “everything is a file” mean in Linux?
  • What is /proc and is it on disk?
  • Difference between /etc, /var and /usr?

Permissions, users & sudo

File permissions: rwx, octal, chmod, chown

Each file has an owner, a group and three rwx triplets (user, group, other) that are often written as octal digits.

  • ls -l shows -rwxr-x---: type, then user, group, other triplets. Digits: r=4, w=2, x=1, so rwx=7, r-x=5, r--=4.
  • On files: r = read content, w = modify content, x = execute. On directories: r = list names, w = create/delete/rename entries, x = enter (cd) and access entries by name.
  • Deleting a file needs w + x on the directory, not write on the file itself.
  • chmod 640 f (octal) or chmod u+x,g-w,o= f (symbolic). chmod -R recurses. chown user:group f changes owner and group (chown needs root); chgrp changes only the group.
  • The kernel checks one class only: if you are the owner, owner bits apply (even if group bits are more generous); else if in the group, group bits; else other. root bypasses most checks.

Interview questions

  • What do r, w and x mean on a directory?
  • Can a user delete a file they don't have write permission on?
  • How does Linux decide which permission triplet applies?

umask, setuid, setgid & sticky bit

umask removes bits from default modes; setuid/setgid change who a program runs as, and the sticky bit protects shared directories.

  • Programs create files asking for 666 and directories asking for 777. The process umask clears bits: mode = requested & ~umask. umask 022 → 644/755; 077 → 600/700.
  • umask is per process and inherited by children. Set it in shell startup files, in a service (UMask= in a systemd unit) or with the umask builtin.
  • setuid (4xxx, s in user x slot): the program runs with the file owner's effective UID. /usr/bin/passwd is setuid root so users can update /etc/shadow. Linux ignores setuid on scripts.
  • setgid (2xxx): on a file it runs with the file's group; on a directory new files inherit the directory's group, great for shared team folders.
  • sticky bit (1xxx, t in other x slot): in a world-writable directory like /tmp (1777), only the file owner, dir owner or root can delete or rename a file.
  • A capital S or T means the special bit is set but the matching x bit is not, which is usually a mistake.

Interview questions

  • What is umask and how is the final permission computed?
  • Explain setuid with an example.
  • How would you set up a shared folder for a team?

Users, groups & sudo

Users and groups are numbers (UID/GID) mapped to names in /etc files; sudo lets allowed users run commands as root with an audit trail.

  • The kernel only knows UIDs and GIDs. Names come from /etc/passwd (user, UID, GID, home, shell) and /etc/group. Password hashes live in /etc/shadow (readable only by root).
  • root is UID 0. System/service accounts usually have UIDs below 1000 and a shell of /usr/sbin/nologin.
  • Each user has one primary group (used for new files) and any number of supplementary groups. id shows them.
  • useradd -m -s /bin/bash alice, passwd alice, usermod -aG docker alice (the -a matters: without it you replace all supplementary groups).
  • sudo runs a command as another user (root by default) after checking /etc/sudoers and /etc/sudoers.d/. Always edit them with visudo, which syntax-checks before saving.
  • su - switches to another user and needs their password; sudo needs your password and logs every command.

Interview questions

  • Difference between su and sudo?
  • Where are users and passwords stored?
  • How do you give a user permission to restart one service without full root?

Processes, signals & services

Processes: PID, PPID, states, ps & top

A process is a running program with a PID, a parent, an owner, open files and a state; ps takes a snapshot and top watches live.

  • Every process has a PID, a parent PPID, a UID, a working directory, an environment, open file descriptors and a state. All of it is visible in /proc/<pid>/.
  • Threads are tasks that share memory with their process; in Linux they are also scheduled entities with their own TID (ps -L, top -H).
  • States (STAT column): R running/runnable, S interruptible sleep (waiting for an event), D uninterruptible sleep (usually disk or NFS I/O), T stopped, Z zombie.
  • ps aux (BSD style) or ps -ef (System V) list all processes. ps -o pid,ppid,stat,%cpu,%mem,cmd --sort=-%cpu builds a custom view. pstree -p shows the tree.
  • top refreshes live: press P (sort by CPU), M (by memory), 1 (per-CPU), k (kill). htop is a friendlier version with a tree view and mouse support.
  • Nice values (-20 to 19) influence CPU priority: higher nice = lower priority. nice -n 10 cmd, renice 5 -p PID. Only root can lower nice.

Interview questions

  • What is the difference between a process and a thread?
  • What are the process states in Linux?
  • ps aux vs ps -ef?

fork/exec, zombies & orphans

New programs start with fork (clone the parent) plus exec (replace the image); a dead child stays a zombie until its parent calls wait().

  • fork() creates a child that is a near-copy of the parent. Memory is shared copy-on-write, so fork is cheap. It returns 0 in the child and the child's PID in the parent.
  • execve() replaces the current process image with a new program. The PID stays the same, and open fds (without close-on-exec) are inherited. That is how the shell sets up redirections before running a command.
  • When a child exits, the kernel keeps a tiny entry with its exit status until the parent calls wait()/waitpid(). Until then it is a zombie (Z, <defunct>). Zombies use no memory or CPU, just a PID slot.
  • An orphan is a child whose parent died first. It is re-parented to PID 1 (or the nearest *subreaper*, like systemd user managers), which reaps it when it exits.
  • You cannot kill a zombie: it is already dead. Fix or kill the parent, so PID 1 adopts the zombie and reaps it.
  • exec cmd in a shell script replaces the shell with cmd (no extra process). Docker entrypoint scripts use exec "$@" so the app becomes PID 1 and receives signals.

Interview questions

  • Explain fork and exec.
  • What is a zombie process and how do you get rid of it?
  • What is copy-on-write in fork?
  • Why should a container entrypoint script end with exec "$@"?

Signals, kill, trap & job control

Signals are small async notifications; SIGTERM asks a process to stop, SIGKILL forces it, and the shell's job control uses signals for &, Ctrl+Z, bg and fg.

  • kill PID sends SIGTERM (15) by default: a polite request the process can catch to clean up. kill -9 PID sends SIGKILL, which the kernel enforces; no cleanup, no flushing, possible corrupted state.
  • SIGKILL and SIGSTOP can never be caught, blocked or ignored. Everything else can have a handler (trap in bash).
  • SIGHUP (1): the controlling terminal closed. Many daemons reuse it to reload config (nginx -s reload, kill -HUP). SIGINT (2) is Ctrl+C, SIGQUIT (3) is Ctrl+\ (core dump), SIGTSTP is Ctrl+Z.
  • cmd & runs in the background. jobs lists jobs, fg %1 brings one to the foreground, Ctrl+Z stops the current one and bg %1 resumes it in the background.
  • Closing the terminal sends SIGHUP to its jobs. nohup cmd & ignores SIGHUP and writes output to nohup.out; disown removes a job from the shell's table; setsid starts a new session. For real services use systemd, tmux or screen.
  • pkill -f pattern and killall name signal by name. kill -0 PID sends nothing but checks if the process exists and you may signal it.

Interview questions

  • Difference between SIGTERM and SIGKILL?
  • How do you keep a process running after you log out?
  • What does trap do in a bash script?
  • A container exits with code 137. What happened?

systemd, systemctl, journalctl & cron

systemd is PID 1 and manages services as units; systemctl controls them, journalctl reads their logs, and cron or systemd timers schedule jobs.

  • systemd manages units: .service, .socket, .timer, .mount, .target. Vendor units live in /usr/lib/systemd/system/ (or /lib/...); your own and overrides go in /etc/systemd/system/.
  • systemctl start|stop|restart|reload|status NAME. enable creates the symlinks so it starts at boot; enable --now does both. mask blocks a unit from being started at all.
  • After editing a unit file run systemctl daemon-reload. Use systemctl edit NAME to create a drop-in override instead of editing vendor files.
  • journald collects stdout/stderr of services plus kernel and syslog messages. journalctl -u nginx -f follows a unit, --since "1 hour ago", -p err, -b (this boot).
  • cron runs commands on a schedule: crontab -e per user, /etc/crontab and /etc/cron.d/ system-wide (those have an extra user field). Fields: min hour day-of-month month day-of-week.
  • Cron jobs run with a minimal environment (short PATH, no .bashrc), so use absolute paths and redirect output to a log. systemd timers are the modern alternative with logging, dependencies and Persistent= catch-up.

Interview questions

  • Difference between systemctl start and systemctl enable?
  • A service fails to start. How do you debug it?
  • My cron job works by hand but not from cron. Why?

Shell: redirection, pipes, text & scripting

stdin/stdout/stderr, redirection & pipes

Every process starts with fd 0, 1 and 2; redirection rewires them to files and pipes connect one process's stdout to the next one's stdin.

  • File descriptors: 0 stdin, 1 stdout, 2 stderr. Programs print results to stdout and errors/diagnostics to stderr, so you can separate them.
  • > overwrite, >> append, < read from file, 2> redirect stderr, &> (bash) both, 2>&1 make fd 2 a copy of fd 1 as it is right now.
  • Redirections are processed left to right: cmd > f 2>&1 sends both to f; cmd 2>&1 > f sends stderr to the terminal (old stdout) and only stdout to f.
  • A pipe a | b connects a's stdout to b's stdin through a kernel buffer (64 KiB by default). Both run at the same time; a writer blocks when the buffer is full.
  • Here-doc <<EOF and here-string <<< "$var" feed text to stdin. tee file copies stdin to a file and stdout. set -o noclobber prevents > from overwriting.
  • Process substitution <(cmd) gives a command's output as a filename: diff <(sort a) <(sort b).

Interview questions

  • What do 2>&1 and > /dev/null 2>&1 mean?
  • How does a pipe work under the hood?
  • Why does sudo echo hi > /etc/motd give “Permission denied”?

Text processing: grep, sed, awk, cut, sort, uniq, xargs, find

Small tools that each do one thing, chained with pipes, can answer most log and data questions in one line.

  • grep filters lines: -i ignore case, -v invert, -r recursive, -n line numbers, -c count, -E extended regex, -o only the match, -l file names, -A/-B/-C N context.
  • sed edits a stream: sed 's/old/new/g', delete lines sed '/^#/d', print a range sed -n '10,20p'. -i edits in place (GNU sed -i, macOS sed -i '').
  • awk splits each line into fields $1..$NF and runs pattern { action }: awk -F: '$3 >= 1000 {print $1}' /etc/passwd. It has variables, arrays and BEGIN/END blocks, ideal for sums and group-by.
  • cut picks fields (cut -d, -f2) or chars; tr translates or deletes characters (tr a-z A-Z, tr -d '\r'); wc counts lines/words/bytes; head/tail take the start/end; tail -f (or -F to survive log rotation) follows a growing file.
  • sort (-n numeric, -r reverse, -k2 by column, -h human sizes, -u unique) and uniq (removes adjacent duplicates, so sort first; -c counts). Classic top-N: sort | uniq -c | sort -rn | head.
  • find walks directories with tests: find /var/log -name '*.log' -mtime +7 -size +100M. xargs turns stdin into arguments: find . -name '*.tmp' -print0 | xargs -0 rm. find -exec cmd {} + does the same without xargs.

Interview questions

  • How do you find the top 10 most frequent IPs in a log file?
  • Difference between grep, sed and awk?
  • What does xargs do and why is it needed?
  • How do you find files larger than 1 GB modified in the last day?

Environment variables, PATH & startup files

Exported variables are copied into child processes; PATH decides where commands are found; login and interactive shells read different startup files.

  • A shell variable (x=1) exists only in the current shell. export x makes it an environment variable, copied into every child process. Children can never change the parent's environment.
  • VAR=value cmd sets a variable only for that one command. env / printenv list the environment; unset VAR removes it.
  • PATH is a colon-separated list of directories searched in order for commands. which -a, type -a and command -v show what will run. The current directory is not on PATH, hence ./script.sh.
  • Login shell (SSH login, bash -l, console): reads /etc/profile, then the first of ~/.bash_profile, ~/.bash_login, ~/.profile. Interactive non-login shell (new terminal tab on most Linux desktops): reads ~/.bashrc.
  • Usual setup: put exports in ~/.bash_profile (or ~/.profile) and make it source ~/.bashrc; put aliases, functions and prompt in ~/.bashrc. Non-interactive scripts read neither (unless BASH_ENV is set).
  • source file (or . file) runs a file in the current shell, so its variables and cd stick. Running ./file uses a child shell and changes vanish.

Interview questions

  • Difference between .bashrc and .bash_profile?
  • Difference between a shell variable and an environment variable?
  • Difference between source script.sh and ./script.sh?

Shell scripting basics: variables, quoting, conditionals, loops, functions

A bash script is a list of commands with variables, tests and loops; exit codes drive the logic and quoting prevents most bugs.

  • Start with a shebang: #!/usr/bin/env bash finds bash on PATH; #!/bin/sh means POSIX sh (dash on Ubuntu), where bash features like [[ ]] and arrays don't exist. Make it executable with chmod +x.
  • Variables: name=value with no spaces around =. Read with "$name". Arguments: $1..$9, $# count, "$@" all args as separate words, $0 script name, $? last exit code, $$ PID, $! last background PID.
  • Quoting: double quotes allow $var and $(cmd) expansion but stop word-splitting and globbing; single quotes are fully literal. Always quote variables: rm "$file".
  • Exit codes: 0 = success, 1–255 = failure. if tests the exit code of a command. && runs the next command on success, || on failure.
  • Tests: [[ -f file ]], -d dir, -z empty string, -n non-empty, == string match (glob in [[ ]]), =~ regex, -eq -lt -gt numbers; (( n > 5 )) for arithmetic.
  • Loops: for f in *.log; do ...; done, while read -r line; do ...; done < file, for ((i=0; i<3; i++)). Functions: name() { local x=$1; ...; return 0; }; they return a status and “return” data by echoing it.

Interview questions

  • What is the shebang line and why use #!/usr/bin/env bash?
  • Difference between single and double quotes in bash?
  • What is the difference between $@ and $*?
  • [ ] vs [[ ]]?

Robust scripts: set -euo pipefail, traps & pitfalls

Strict mode makes scripts fail fast on errors, unset variables and broken pipelines, but each flag has exceptions you must know.

  • set -e (errexit): exit when a command fails. It is ignored in if/while conditions, in commands before &&/||, and in negated commands. Functions called inside those contexts also lose it.
  • set -u (nounset): using an unset variable is an error. Use ${VAR:-} when “unset” is a legal value.
  • set -o pipefail: a pipeline's status is the last non-zero status of any stage, not just the last command's. Without it curl bad | tee log “succeeds”.
  • Combined as set -euo pipefail at the top of every script. Add trap 'echo "failed at line $LINENO" >&2' ERR for a useful error message and trap cleanup EXIT for temp files and locks.
  • Pitfalls: local x=$(cmd) hides cmd's failure (the status is that of local); split into local x; x=$(cmd). grep returns 1 on no match, so grep ... || true when that's fine. ((count++)) returns 1 when count was 0.
  • Make scripts idempotent (safe to re-run: mkdir -p, ln -sf, check before create), use mktemp for temp files, flock to stop overlapping cron runs, and run ShellCheck in CI.

Interview questions

  • What does set -euo pipefail do?
  • When does set -e not stop the script?
  • Why is pipefail important?
  • How do you stop a cron script from running twice at the same time?

System resources, networking & troubleshooting

Load average, memory, swap, OOM killer & disks

Read load against CPU count, memory via the “available” column, and disk via df (space and inodes), du (who uses it), lsblk and mount.

  • Load average (uptime, /proc/loadavg) is the exponentially-damped average of tasks that are runnable or in uninterruptible sleep (D), over 1, 5 and 15 minutes. Divide by the number of CPUs (nproc). Load 8 on 8 cores is full; on 2 cores tasks are queuing.
  • On Linux high load with low CPU usage usually means tasks stuck in D state on disk or NFS I/O. Check wa in top, vmstat 1 and iostat -x 1.
  • free -h: used, free, buff/cache and available. Linux fills spare RAM with page cache, so low “free” is normal; available estimates what apps can still get without swapping.
  • Swap is disk-backed overflow memory. Some swap use is fine; constant swap in/out (si/so in vmstat) means thrashing. vm.swappiness tunes how eagerly the kernel swaps.
  • When memory can't be reclaimed, the OOM killer picks a victim by oom_score (mostly memory size, adjusted by oom_score_adj from -1000 to 1000) and sends SIGKILL. dmesg -T | grep -i 'killed process' shows it. Containers hit their cgroup limit the same way.
  • Disks: lsblk shows block devices and partitions, df -h free space per mounted filesystem, df -i inodes, du -sh dir usage of a tree, mount/findmnt mounts, and /etc/fstab (use UUIDs) persists them.

Interview questions

  • What is load average and what is a “good” value?
  • Load is 20 on a 4-core box but CPU is 10% used. What's going on?
  • free shows almost no free memory. Is that a problem?
  • Difference between df and du?

Networking commands: ip, ss, curl, dig, ping, traceroute, nc

Debug a network path bottom-up: interface and route (ip), DNS (dig), reachability (ping, traceroute), port (nc, ss), then the application (curl).

  • ip addr (interfaces and IPs), ip route (routing table, default gateway), ip link (up/down, MTU). They replace the deprecated ifconfig and route from net-tools.
  • ss -tulpn lists listening TCP/UDP sockets with the owning process (-p needs root to see other users' processes). ss -tan state established shows connections. ss replaces the older netstat.
  • ping tests ICMP reachability and latency; many clouds and firewalls block ICMP, so no reply ≠ host down. traceroute/tracepath/mtr show each hop to find where packets stop or slow down.
  • dig example.com (or dig +short, dig @8.8.8.8, dig MX) queries DNS directly; nslookup and host are simpler. getent hosts name resolves the way apps do (including /etc/hosts, via nsswitch).
  • curl -v https://host/path shows DNS, TCP, TLS and HTTP headers; -I headers only, -L follow redirects, -o save, -w '%{http_code}' print fields. wget is mainly for downloads.
  • nc -zv host 5432 checks if a TCP port is open; nc -l 9000 opens a quick listener. Other tools: tcpdump -i any port 443 captures packets, lsof -i :8080 maps ports to processes, firewall via iptables/nftables/ufw/firewalld.

Interview questions

  • How do you check which process is listening on port 8080?
  • A service can't reach the database. How do you debug it?
  • Difference between netstat and ss?
  • What happens when you run curl https://example.com?

SSH, keys, scp & rsync

SSH gives an encrypted remote shell; key-based auth proves identity with a private key that never leaves your machine; scp/rsync copy files over it.

  • ssh-keygen -t ed25519 -C you@example.com creates a key pair: ~/.ssh/id_ed25519 (private, keep 600) and .pub (public). ssh-copy-id user@host appends the public key to the server's ~/.ssh/authorized_keys.
  • Login with keys: the server sends a challenge, the client signs it with the private key, the server verifies with the stored public key. The private key is never sent.
  • On first connect you accept the server's host key, stored in ~/.ssh/known_hosts. A later mismatch warning means the server was rebuilt or a man-in-the-middle; verify before deleting the entry.
  • Hardening /etc/ssh/sshd_config: PasswordAuthentication no, PermitRootLogin no (or prohibit-password), restrict users, then sshd -t and reload. Permissions: ~/.ssh 700, authorized_keys 600, or sshd ignores them.
  • ~/.ssh/config stores host aliases, users, keys and ProxyJump (bastion hosts). ssh-agent holds decrypted keys in memory; agent forwarding (-A) is convenient but risky on untrusted hosts.
  • Copying: scp file host:/path is simple; rsync (rsync -avz --delete src/ host:dst/) transfers only differences, can resume and preserve permissions, and is preferred for directories. Tunnels: -L local forward, -R remote forward, -D SOCKS proxy.

Interview questions

  • How does SSH key-based authentication work?
  • What is known_hosts and what does “REMOTE HOST IDENTIFICATION HAS CHANGED” mean?
  • scp vs rsync?
  • How do you securely reach a database in a private subnet?

Troubleshooting scenarios: disk full, high CPU, port in use, slow server

Have a repeatable checklist: confirm the symptom, find the resource that is saturated, find the process responsible, fix safely, then prevent it.

  • Disk full: df -h to find the filesystem, df -i for inodes, du -xh --max-depth=1 / | sort -h to drill down. Usual suspects: logs in /var/log, Docker images/volumes (docker system df), core dumps, old kernels, journal (journalctl --vacuum-size=500M).
  • Space not freed after deleting a big log? A process still has it open. lsof +L1 (or lsof | grep deleted) finds it; restart/reload the process or truncate via : > /proc/<pid>/fd/<n>. Next time truncate with : > file instead of rm, and set up logrotate.
  • High CPU: top/htop sorted by CPU, check us vs sy vs wa vs st. For the busy process: top -H -p PID for threads, strace -cp PID for syscalls, perf top, or language tools (jstack, py-spy).
  • Port already in use (EADDRINUSE): ss -ltnp | grep :8080 → PID → is it an old instance, another service or a zombie container? Stop it properly; for restarts in your own code set SO_REUSEADDR to avoid waiting on TIME_WAIT.
  • Server slow (USE method: Utilization, Saturation, Errors for each resource): uptime → dmesg -T | tail → vmstat 1 → mpstat -P ALL 1 → pidstat 1 → iostat -xz 1 → free -m → sar -n DEV 1 → top. Then app logs and dependencies (DB, DNS, downstream APIs).
  • Always: check what changed (deploys, config, traffic), look at logs (journalctl -p err -b), fix the symptom safely, then write down the root cause and add monitoring or alerts.

Interview questions

  • A server says “No space left on device”. Walk me through it.
  • A process is using 100% CPU. What do you do?
  • Your app fails to start with “Address already in use”. How do you fix it?
  • Users say the server is slow. How do you approach it?