Linux

Linux interview questions

Questions you may be asked in a Linux interview, each with an answer that explains the why. Read them, then take the Linux test to see how you do under a clock.

Practice first in a hands-on lab

Disks and logs

You get an alert that / is 95% full on a production server. You must free space safely without taking the service down. What do you do?

First I find out what is using space instead of deleting blindly. I run df -h to confirm which filesystem is full, then du -xh / --max-depth=1 | sort -h and drill down into the biggest directory. The -x flag keeps du on one filesystem. Usual culprits are logs in /var/log, old package caches, and core dumps. I would compress or delete old, already-rotated logs. I would truncate in place (truncate -s 0 file) any active log that is not needed, or force a logrotate run that signals the process to reopen its logs. I would also run journalctl --vacuum-size=500M or clear the package cache. I would not delete or gzip a file a running process still has open, because the space is not freed while the process holds it. If a deleted file still holds space, lsof +L1 shows it. I can release the space without downtime by truncating it through the process's descriptor (: > /proc/<PID>/fd/<N>) or by triggering a graceful reload so the process reopens its files. A restart is the last resort, done in a way that avoids an outage. Afterward I would fix the cause, such as adding logrotate settings or monitoring. Interviewer is listening for: investigating before deleting, awareness of open deleted files and how to release them without downtime, and a long-term fix, not just a one-time cleanup.

Disk space on /var/log keeps growing even though logrotate is installed. How do you figure out why rotation is not keeping up, and what would you check?

I start with du -xh /var/log --max-depth=1 | sort -h to see which logs are large. If /var/log/journal is big, logrotate is not involved: I check journalctl --disk-usage and set SystemMaxUse= in /etc/systemd/journald.conf. For regular log files, I check whether a config exists for them in /etc/logrotate.d/. Then I run logrotate -d /etc/logrotate.conf as a dry run to see what it would do. I look at the state file for last rotation times. That is /var/lib/logrotate/status on Debian/Ubuntu and /var/lib/logrotate/logrotate.status on RHEL/Fedora. I confirm the scheduler runs with systemctl status logrotate.timer, or check the cron job on older systems. Common causes are:
- a missing config for a custom app
- a rotation size or frequency that is too lax
- no compress
- the app keeping the old or deleted file open, so the space is not freed

I confirm the open-file case with lsof +L1 and fix it with a postrotate reload or signal. copytruncate is the fallback, and it can lose a few lines. Interviewer is listening for: a methodical approach, using the debug flag, awareness of open file handles after rotation, and knowing that the journal is separate from logrotate.

Your monitoring shows a server's root filesystem has run out of inodes, though df -h shows free space. How do you find the cause and fix it?

I confirm with df -i, which shows inode use per filesystem. Running out of inodes usually means huge numbers of tiny files, such as session files, mail queues, cache directories, or runaway logs. To find where, I count inodes per directory while staying on the root filesystem, for example du --inodes -x / | sort -n | tail -20, or find / -xdev -printf '%h\n' | sort | uniq -c | sort -rn | head to see which directories directly hold the most entries. I start at / with -x/-xdev so the search doesn't descend into other mounted filesystems such as /proc, /sys or a separate /home, which don't use root's inodes. Then I drill into the biggest directory. Once I identify the source, I check whether the files are safe to delete, such as old temp or cache files. I remove them with find ... -delete rather than rm *, which can fail with 'Argument list too long' on huge directories. Then I fix the root cause, like a missing cleanup job or an application bug, and add inode alerts. Interviewer is listening for: knowing df -i, a method to locate the files that stays on the affected filesystem, and fixing the cause, not just the symptom.

A database server's data partition is at 92% and growing. You cannot add disk today. How do you decide what is safe to remove or move, and what would you avoid doing?

First I find where the space is: df -h to confirm the filesystem, then du -xh --max-depth=1 /path | sort -h to drill down. I look for safe, regenerable data such as old rotated logs, core dumps, package caches, and expired backups, and I confirm with the owners before deleting. Compressing old logs or moving them to other storage is safer than deleting. I check lsof +L1 for deleted files still held open by a process. That space only comes back when the process closes the file, through a restart or a reload that reopens its logs. Alternatively, I can carefully truncate the file through /proc (e.g. : > /proc/PID/fd/N) if losing its contents is acceptable. I avoid deleting database files, WAL or binary logs by hand, because that can corrupt data or break replication and recovery; I use the database's own purge and retention tools. I also avoid rm -rf with wildcards on production. Afterwards I plan the permanent fix: proper log rotation and retention, backup and binlog/WAL retention policies, disk-usage alerting, and a capacity request. The interviewer is listening for caution, verification before deletion, and a plan for a permanent fix.

Files and permissions

A teammate says a web app on your server cannot read uploaded files in /srv/app/uploads. You run ls -ld /srv/app/uploads and see drwx------ 2 deploy deploy 4096 Mar 3 10:02 /srv/app/uploads. The app runs as the www-data user. How would you fix it, and how would you decide between the options?

The directory mode is 700 and it is owned by deploy, so www-data cannot even enter it.

First I would confirm the app's real user with ps -o user= -p <pid>. Then I would check every parent directory is traversable with namei -l /srv/app/uploads.

Then I would pick the narrowest fix that matches who writes and who reads.

**Option 1: shared group.** Use this when deploy (or another process) writes and www-data reads.
- Put the directory in a group www-data belongs to. That can be www-data's own group or a dedicated shared group with both users added. For example: chgrp www-data /srv/app/uploads.
- Set chmod 2750 on the directory, or 2770 if the app must also write. Directories need the execute bit to access anything inside, and read alone only lists names.
- The setgid bit (the 2) makes new files inherit the directory's group.

**Option 2: POSIX ACLs.** Use this when you don't want to change the group.
- Grant access now: setfacl -m u:www-data:rX /srv/app/uploads.
- Cover future files with a default ACL: setfacl -d -m u:www-data:rX /srv/app/uploads.

**Option 3: change ownership.** Use this if the app itself is the uploader and the sole user. Make www-data the owner.

Whichever option I choose, I would fix the existing files, not just the directory. They keep their own modes, so a deploy-owned 600 file stays unreadable. For example: chgrp -R www-data /srv/app/uploads && chmod -R g+rX /srv/app/uploads.

I would also check the umask of the process that writes uploads, so new files get group read.

I would avoid chmod 777, because it gives every user on the system access.

Interviewer is listening for:
- least-privilege thinking
- the execute bit on directories
- that directory permissions don't change file permissions
- inheritance for new files (setgid, default ACLs, umask)
- checking parent paths
- refusing the lazy 777 fix

You need a directory /srv/projects where everyone in the devs group can create files, and where every new file automatically belongs to devs so teammates can edit each other's work. How do you set it up and why does it work?

I would run chgrp devs /srv/projects, then chmod 2775 /srv/projects (or 2770 if others should have no access). The 775 part gives the group read, write, and execute on the directory. Write plus execute on a directory is what allows creating, renaming, and deleting entries in it. The leading 2 is the setgid bit. On a directory, it makes new files and subdirectories inherit the directory's group instead of the creator's primary group. New subdirectories also inherit the setgid bit itself, so this carries down the tree. Without it, new files would get each user's primary group, and unless that group happens to be devs, teammates could not edit them through group permissions. Group write on the new files also depends on each user's umask, so I would check that it is 002. Alternatively, I would set a default ACL with setfacl -d -m g:devs:rwx /srv/projects, which grants group access to newly created files regardless of umask. Existing files would still need chgrp/chmod or a regular setfacl -m. Interviewer is listening for: setgid on directories, the umask caveat, and understanding that directory write permission controls creation and deletion.

You inherit a server and find a file /etc/app/db.conf containing a database password, mode 644. How do you decide what the permissions and ownership should be, and how do you change them without breaking the app?

First I find out which account actually opens the file. I check the systemd unit's User=/Group=/SupplementaryGroups= lines and the running process with ps -o user=,group= -p <pid>. I also confirm whether the file is read before privileges are dropped: some daemons start as root and then switch user, and systemd's EnvironmentFile= is read by systemd itself as root. The file only needs to be readable by that one account. My preferred setup is chown root:app /etc/app/db.conf and chmod 640 /etc/app/db.conf, where app is a group the service user belongs to. With that, the app can read the file but cannot modify it or change its mode. If the file is read as root, root:root 600 is enough. If the app genuinely owns its config, app:app 600 works. The owner and mode have to match: owner root with mode 600 would lock out a non-root app. I also check that the parent directories allow traversal (namei -l /etc/app/db.conf). I check SELinux/AppArmor labels too, using ls -Z and restorecon if needed. Then I restart the service, or use a reload that is documented to re-read config, and confirm with systemctl status and journalctl -u <service> that it started and connected. Because the file was world-readable, I treat the password as exposed and rotate it. I also check whether backups, config management, or other users hold copies. Interviewer is listening for: least privilege, identifying the real reading account first, matching ownership to mode, verifying after the change, and rotating the exposed secret.

You are asked to set up a directory where a team of five engineers can collaborate on files, while everyone else on the server has no access at all. Describe how you would configure it and how you would verify it.

I would create a group, say eng, add the five users with usermod -aG eng user, then create the directory, run chown root:eng /srv/team, and set chmod 2770 /srv/team. The 770 gives owner and group full access and others nothing. The setgid bit (the 2) makes new files inherit the eng group so teammates can edit each other's work. I would also consider umask 007 or default ACLs with setfacl -d so new files are group-writable. To verify, I run ls -ld /srv/team, then use sudo -u as a member and a non-member to test create and read access, and id to confirm group membership. Users need to log in again for new groups to apply. The interviewer is listening for setgid understanding, least privilege, and actually testing the result.

Processes and services

You run systemctl restart nginx and it fails. Walk me through exactly how you would find out why, and what you would look at first.

I would start with systemctl status nginx to see the state, exit code, and the last few log lines. Then I would read the full journal for that unit with journalctl -u nginx -b --no-pager (or -e to jump to the end), because status truncates output. Common causes are a config syntax error, a port already in use, or a permissions problem on a cert or log file. I would run nginx -t to validate the config, and ss -tlnp | grep ':80' to see whether something else holds the port. If I had just edited a unit file, I would check that I ran systemctl daemon-reload. Interviewer is listening for: using the logs rather than guessing, a logical order of checks, and knowing the specific tools (journalctl, ss, config test) instead of just retrying the restart.

A Java service managed by systemd keeps getting killed every few hours, and the systemctl status output just says the process exited with signal 9. How do you find out whether the kernel's OOM killer did it, and what would you do about it?

Signal 9 with nobody running kill usually points to an OOM kill. First, check systemctl status. On recent systemd it may already say Failed with result 'oom-kill'. Then check the kernel log, not just the service log. journalctl -k | grep -i 'out of memory' or dmesg -T | grep -i kill will show lines like 'Out of memory: Killed process 2231 (java)'. 'Memory cgroup out of memory' means a cgroup limit was hit rather than the whole system running out. These lines give the time, the victim and memory figures. On distros that run systemd-oomd (Fedora, Ubuntu 22.04+), also check journalctl -u systemd-oomd, because it kills cgroups under memory pressure and logs there instead. Next, compare against free -h and the service's memory use over time, for example with systemctl status memory lines or monitoring. Then work out the cause. The heap may be sized too large for the box (the JVM also uses memory beyond -Xmx: metaspace, thread stacks, direct buffers). There may be a leak. Or another process may be using the memory. Fixes depend on the cause. You can right-size the JVM with -Xmx or -XX:MaxRAMPercentage, fix the leak, or add RAM or swap. You can also set MemoryMax= in the unit. That will not stop kills if the service still exceeds the limit, but it contains the OOM event to that service and protects the rest of the host, provided the JVM is sized to fit under it. I would not just restart it and move on. Interviewer is listening for: knowing to check kernel logs (and systemd-oomd), not only service logs, and a fix tied to the cause rather than a blind restart.

A colleague says a service you manage with systemd is stuck in a restart loop, starting and crashing every few seconds. How do you investigate and stop the damage while you debug?

First I take a quick look with systemctl status myapp to see the state, exit code, and the last few log lines. Then I stop the loop right away with systemctl stop myapp. Constant restarts can fill logs, hammer a database, or hit start-rate limits, and the crash output stays in the journal after the unit is stopped. If it must stay down across reboots, I also disable it, or mask it if nothing should be able to start it. Then I read the full output with journalctl -u myapp -b --no-pager, looking for the first error rather than the repeats. Next I check recent changes: config edits, missing environment files, permissions, ports in use with ss -tlnp, and the unit's Restart= settings. I can run the binary by hand as the service user to reproduce the crash. Interviewer is listening for: stopping the loop early, reading logs before guessing, finding the first failure, and reproducing as the service user.

Users report that a server is unreachable over SSH, but you can still get to it through a console. What do you check from the console to figure out why?

I start by confirming the SSH daemon is running: systemctl status sshd on RHEL-family systems, or systemctl status ssh on Debian and Ubuntu. On newer Ubuntu (22.10+), SSH is socket-activated, so I also check systemctl status ssh.socket; an inactive ssh.service there is normal. If the service has failed, I read journalctl -u sshd (or -u ssh) for the reason, often a bad config, which I validate with sshd -t. Next I check that something is listening on the expected port with ss -tlnp 'sport = :22', using the configured port if it is not 22, and confirm it matches what clients use. Then I look at the firewall with nft list ruleset, iptables -L, firewall-cmd --list-all, or ufw status, and check the network with ip a and ip r. I also check whether the disk is full or the system is out of memory, since either can break logins or get sshd killed. Finally, the auth logs (/var/log/auth.log on Debian/Ubuntu, /var/log/secure on RHEL, or journalctl) show rejected attempts, including blocks from tools like fail2ban. Interviewer is listening for: working from the service outward in a logical order, and knowing the right tools.

A web server's memory use climbs steadily until it starts swapping heavily and response times collapse. You have SSH access while it is still barely responsive. How do you find out what is consuming memory, and what do you do first to stabilize things?

I would start with free -h to confirm memory and swap pressure, then ps aux --sort=-%mem | head or top (press M) to see the biggest consumers. vmstat 1 shows whether swapping (si/so) is active. If one process is clearly runaway, I check whether it is a known service and restart it with systemctl restart rather than killing it blindly, so dependencies and logs stay clean. If the kernel already killed something, journalctl -k | grep -i oom tells me. Stabilizing comes first, root cause second: I capture evidence (ps output, logs) before restarting so I can investigate leaks later. Then I add monitoring and memory limits, such as MemoryMax= in the unit file. The interviewer is listening for a methodical order: diagnose with tools, preserve evidence, make a safe fix, then prevent recurrence.

The shell

You have a 2 GB web server log, access.log, with lines starting with the client IP address. How would you find the top 5 IP addresses by request count using the command line, and why does each part of the pipeline matter?

I would run: awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -5. The awk command extracts the first field, the IP. sort is required first because uniq only collapses adjacent duplicate lines. uniq -c prefixes each unique IP with its count. The second sort -rn orders numerically from highest to lowest, and head -5 keeps the top five. awk, uniq and head process the data as a stream. sort has to see all of its input before it can output anything, but GNU sort uses an external merge sort with temporary files on disk, so the 2 GB never has to fit in memory or be opened in an editor. Because the second sort works only on the short list of unique IPs, it is cheap. For speed I could use LC_ALL=C sort, which avoids locale-aware collation. An alternative that avoids the big sort entirely is to count in awk with an associative array: awk '{c[$1]++} END {for (ip in c) print c[ip], ip}' access.log | sort -rn | head -5. Interviewer is listening for: correct pipeline order, understanding why the first sort is needed, comfort with command-line text tools over opening the file, and being able to explain each step.

You need to rename every .jpeg file in a directory to .jpg, and some filenames contain spaces. How do you do it safely from the shell, and what mistakes do you avoid?

I would use a loop with quoting: for f in *.jpeg; do mv -- "$f" "${f%.jpeg}.jpg"; done. The glob expands to whole filenames, so spaces are not split, which would happen with for f in $(ls *.jpeg). Quoting "$f" keeps each name as one argument. ${f%.jpeg} strips the suffix using parameter expansion, so no external tool is needed. The -- guards against names starting with a dash being read as options. Before running it for real, I would put echo before mv to preview, or use mv -n to avoid overwriting an existing file. Interviewer is listening for: correct quoting, avoiding parsing ls output, and the habit of testing a bulk operation before running it.

You have a CSV export orders.csv with a header row, and the third column is a status such as shipped or failed. How would you count how many orders have each status from the command line?

I would skip the header, extract the third column, then sort and count: tail -n +2 orders.csv | cut -d, -f3 | sort | uniq -c | sort -rn. tail -n +2 drops the header so it is not counted. cut pulls the status field using a comma delimiter. sort is required before uniq -c because uniq only collapses adjacent duplicates. The final sort -rn puts the most common statuses first. An alternative is awk -F, 'NR>1{c[$3]++} END{for(k in c) print k, c[k]}' orders.csv. I would mention a limitation: if fields can contain quoted commas, both cut and a plain awk -F, split in the wrong place. In that case I would use a CSV-aware tool, such as GNU awk with FPAT (or --csv in gawk 5.3+), csvkit (csvcut), mlr, or Python's csv module. Interviewer is listening for: why sort comes before uniq, handling the header, and awareness of CSV edge cases.

Your manager hands you a 3 GB application log and asks which error messages are most common today. How would you work that out from the command line, and why would you build it that way?

I would filter first, then summarize. For example: grep ' ERROR ' app.log | sed 's/[0-9]\+/N/g' | sort | uniq -c | sort -rn | head -10. Grep narrows the data early so later steps handle less. The sed step replaces numbers like IDs and timestamps so similar messages group together; without it every line looks unique. sort is required before uniq -c because uniq only collapses adjacent duplicates. The final sort -rn ranks by count and head limits output. If the log has a date, I would filter for today first. I stream rather than open the file in an editor, because it is big. The interviewer is listening for understanding of why each stage exists, especially the sort before uniq, and awareness of normalizing data so counts are meaningful.

Users and groups

You just added the user maria to the docker group with usermod -G docker maria. She says she can no longer use sudo, even though she could an hour ago. What most likely happened, and how do you fix it?

The -G option replaces the user's entire supplementary group list. It does not add to it. Maria was probably in sudo (or wheel on Red Hat-style systems), and that membership was wiped out when she was set to only docker. To fix it, run usermod -aG sudo maria (use wheel on RHEL, Fedora, or Rocky). The -a flag means append. Then check with id maria or groups maria. She must log out and back in before the new group list applies to her session. In the future, always pair -a with -G. Check the current groups with id before changing anything. The interviewer is listening for: knowing that -G without -a overwrites groups, naming the right admin group for the distribution, verifying with id, and remembering that group changes need a new login session.

A new developer joins and needs shell access plus the ability to run commands as root on one server. How do you set that up, and how do you keep it secure and auditable?

I would create the account with useradd -m -s /bin/bash alice (or adduser), then set up key-based SSH by placing her public key in ~alice/.ssh/authorized_keys with 700 on .ssh and 600 on the file, and owned by her. I would avoid sharing passwords. For root access I would add her to the sudo or wheel group, depending on the distribution, or better, write a limited file in /etc/sudoers.d/ edited with visudo that permits only the commands she needs. Sudo logs each command to the auth log or journal, which gives an audit trail. Interviewer is listening for: key-based login, correct SSH permissions, least privilege via sudo rules, using visudo to avoid lockouts, and awareness of auditing.

An employee leaves the company. What do you do on a Linux server to remove their access, and what do you deliberately not do right away?

First I lock access: usermod -L -e 1 username or chage -E 0, remove their SSH keys from ~/.ssh/authorized_keys, and end active sessions with pkill -KILL -u username or loginctl terminate-user. I also check for cron jobs, at jobs, and sudoers entries, and rotate any shared secrets they knew. What I do not do immediately is run userdel -r. Their files may be needed, they may own running services or data, and deleting loses evidence if there is an investigation. I would find owned files with find / -user username, reassign what is needed with chown, archive the home directory, and delete the account later. Interviewer is listening for: locking before deleting, covering keys and scheduled jobs, and caution about data ownership and auditing.

A developer says they can no longer SSH into a server with their key, though it worked yesterday. You have root access. Walk me through how you troubleshoot it.

I would check the server side first, since logs show the real reason. journalctl -u ssh (or -u sshd on RHEL-family systems) or /var/log/auth.log (or /var/log/secure) usually says why, such as bad ownership or a locked or expired account. Then I verify the account: getent passwd user, passwd -S user or chage -l user for locked or expired status, and that the shell is valid. Next, permissions: the home directory must not be group- or world-writable, ~/.ssh should be 700, and authorized_keys 600, all owned by the user, or sshd (with StrictModes, the default) ignores the key. I confirm the key is present in authorized_keys. I check the effective sshd configuration (sshd -T) for changes to PubkeyAuthentication, AuthorizedKeysFile, or AllowUsers/AllowGroups/DenyUsers. From the client, ssh -v shows which keys are offered and where authentication fails. The interviewer is listening for a logs-first approach and knowledge of the strict permission rules.