Ravindra BagaleCourses & study guides मराठी Track your progress

AWS Cloud

Linux Commands A-Z Part 8: uniq, useradd, usermod, vim, vmstat, xargs, yum, zcat and More with Examples

This is Part 8, the last part of the Linux Commands A-Z reference: uniq to zip. These commands count and de-duplicate data, show uptime and load, create, change and remove users, build LVM volume groups, edit files in vim, watch memory and CPU trends, see who is logged in, repeat a command on a timer, count lines, find where a program lives, run commands on many files with xargs, compress with xz, answer prompts with yes, install packages with yum and read compressed logs with zcat. Every command has why, what, an options table and step-by-step examples with real output and its meaning. With this part the A-Z reference is complete, and the index page links every command to its section or to the chapter that already covers it in depth.

In this chapter

  • Count and de-duplicate data with sort, uniq and wc
  • Read load with uptime, w and vmstat
  • Manage users with useradd, usermod and userdel
  • Build storage with vgcreate
  • Edit config files fast in vim
  • Repeat checks with watch and batch work with xargs
  • Find programs with which, whereis and whoami
  • Compress with xz, read with zcat and install with yum

1. An everyday example: a Pune housing society office

The secretary removes duplicate names from the visitor book, counts the entries, checks how long the lift has run without a break, adds new members, changes a flat owner, removes someone who sold the flat, joins two parking areas into one, edits the notice board, checks the water tank level every hour, sees who is in the office right now, and stores old registers in tight bundles that can still be read.

Duplicates are uniq, counting is wc, the lift is uptime, members are useradd, usermod and userdel, joined parking is vgcreate, the notice board is vim, the hourly tank check is watch and vmstat, who is in is w and who, and the bundles are xz and zcat.

Onboarding a new team member end to enduseradd -musermod -aGwhoami checkyum install toolsw: logged in?wc on audit log
Each step uses a command from this part.

2. A log report in one line using Part 8 commands

Before the deep dives, see how these commands chain into a real report.

Read compressed logs, pick a field, count, rank.

StepCommand
Read old gz logszcat access.log.*.gz
Pick IPscut -d" " -f1
Groupsort
Countuniq -c
Ranksort -rn | head
  1. Run the report.
zcat access.log.*.gz | cut -d" " -f1 | sort | uniq -c | sort -rn | head -3

Output:

  9120 10.0.4.22
  3311 10.0.4.9
   870 203.0.113.7

10.0.4.22 sent the most requests.

  1. Count total lines.
zcat access.log.*.gz | wc -l

Output:

48211

About 48 thousand requests in old logs.

3. A user and package audit using Part 8 commands

Security teams in banks, hospitals and SaaS companies ask every month: who can log in, who is logged in now, which tools are installed and where they live. This section answers all of that with Part 8 commands only, so you can run it on any server in a few minutes and paste the output into an audit ticket.

Count real users, list sessions, check tools, check packages, and watch the result for changes.

Audit questionCommandWhat a good answer looks like
How many login users?grep -c "/bin/bash$" /etc/passwd4
Who is on now?w -hravi pts/0 10.0.4.9 ...
Which shell am I?whoami; echo $SHELLravi /bin/bash
Where is the tool?which aws; whereis aws/usr/local/bin/aws
Is the package up to date?yum check-update opensslno output means current
Count failed loginsgrep -c "Failed password" /var/log/securea small number
  1. List shell users and count them.
grep "/bin/bash$" /etc/passwd | cut -d: -f1 | sort | uniq | wc -l

Output:

4

Four accounts can open a shell. Compare this with the approved list from HR; any extra name is a finding.

  1. Rank failed login sources.
grep "Failed password" /var/log/secure | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn | head -3

Output:

    312 203.0.113.50
     41 198.51.100.7
      3 10.0.4.9

One outside IP tried 312 times. Block it in the security group and keep the output as evidence.

  1. See who is logged in and what they run.
w

Output:

 21:10:04 up 41 days,  3:02,  2 users,  load average: 0.31, 0.28, 0.25
USER     TTY      FROM         LOGIN@   IDLE   WHAT
ravi     pts/0    10.0.4.9     20:55    0.00s  w
neha     pts/1    10.0.4.22    19:40    1:10m  vim app.yml

Two people are on. Neha has been idle for over an hour inside vim; ask before you restart anything she may be editing.

  1. Check tools in a loop with xargs.
echo aws git docker jq | xargs -n 1 which

Output:

/usr/local/bin/aws
/usr/bin/git
/usr/bin/docker
/usr/bin/which: no jq in (/usr/local/bin:/usr/bin)

jq is missing. Install it with sudo yum install -y jq and run the check again.

  1. Watch the session count during a change window.
watch -n 10 "who | wc -l"

Output:

Every 10.0s: who | wc -l

2

The screen refreshes every 10 seconds. If the number jumps during a maintenance window, someone new has logged in and you should check who.

4. Industry recipes with Part 8 commands

The same small commands solve very different problems in retail, healthcare, finance, telecom and manufacturing. Seeing them in real settings helps you remember them for interviews and for on-call nights.

Five recipes, each with the command, the output and what to do next.

IndustryProblemCommand
Retailsort orders.csv | uniq -dduplicate orders
Healthcarezcat hl7.log.gz | wc -lmessage count
Financevmstat 5 3batch load
Telecomxz -T0 cdr.logarchive
Manufacturingwatch -n 30 ls sensor/new files
  1. Retail: find duplicate order ids.
cut -d, -f1 orders.csv | sort | uniq -d

Output:

ORD-88121
ORD-90412

Two orders were saved twice. Send the ids to the payments team before customers are charged again.

  1. Healthcare: count lab messages in yesterday's log.
zcat hl7-2026-10-26.log.gz | grep -c "^MSH"

Output:

18422

About 18 thousand lab messages arrived. If the usual number is 25 thousand, ask the lab interface team what stopped.

  1. Finance: check the night batch server.
vmstat 5 3

Output:

procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
 3  4      0 412000  20100 3100000    0    0  9100  4200  900 1500 22  6 30 42  0

wa is 42 and b is 4: the batch is waiting on disk, not CPU. Move it to faster storage or spread the jobs.

  1. Telecom: compress call records with all CPUs.
xz -T0 -k cdr-2026-10.log && ls -lh cdr-2026-10.log*

Output:

-rw-r--r-- 1 ops ops 9.8G cdr-2026-10.log
-rw-r--r-- 1 ops ops 610M cdr-2026-10.log.xz

10 GB became 610 MB. Keep the original until you upload and check the .xz file.

  1. Manufacturing: wait for sensor files.
watch -n 30 "ls sensor/ | wc -l"

Output:

Every 30.0s: ls sensor/ | wc -l

144

144 files have arrived. When the number stops growing during a shift, the plant gateway may be down.

5. uniq: Remove or count repeated lines

Write web, db, web on separate lines. uniq -c counts adjacent runs, so the two web entries appear separately. Sort and run it again to see the total, 2 for web and 1 for db. Leave the original order in place if you are tracking how long each sequential state lasted. Pick the method based on the question the count should answer.

uniq in depth: remove and count duplicates

Which IP hit the site most? How many orders per city? Which error repeats? Sort the lines, then uniq -c counts them.

uniq removes adjacent duplicate lines, so input is usually sorted first. -c prefixes counts, -d shows only duplicated lines, -u only unique ones, -i ignores case, -f N skips fields. sort -u is a shortcut when you only need unique lines.

Common options

OptionWhat it does
sort | uniqUnique lines.
-cCount each.
-dOnly repeated.
-uOnly once.
-iIgnore case.
  1. Top IPs.
cut -d" " -f1 access.log | sort | uniq -c | sort -rn | head -3

Output:

   4210 49.36.12.8
    980 103.21.4.7
    120 10.0.1.5

One IP sends most traffic; check if it is a bot.

  1. Orders per city.
cut -d, -f2 orders.csv | sort | uniq -c

Output:

  310 Mumbai
  452 Pune

Pune leads.

  1. Duplicated user ids.
sort ids.txt | uniq -d

Output:

u1042

One id appears twice: a data bug.

  1. Without sort.
printf "a\nb\na\n" | uniq

Output:

a
b
a

Not adjacent, so not removed: sort first.

Practise this in the tasks below: Practice tasks

Real use: A Laxmi Road jeweller counts daily sales per item with sort | uniq -c on the billing export.

6. uptime: Show uptime and load

uptime in depth: how long and how loaded

Did the server reboot last night? Is it overloaded right now? uptime answers in one line.

uptime prints current time, how long since boot, logged-in users and load average for 1, 5 and 15 minutes. Compare load with the CPU count (nproc): load above it means work is queuing. -p pretty format, -s boot time.

Common options

OptionWhat it does
uptimeOne line.
-pPretty.
-sBoot time.
nprocCPU count.
cat /proc/loadavgRaw values.
  1. Check.
uptime

Output:

 11:42:10 up 41 days,  3:10,  2 users,  load average: 0.42, 0.51, 0.48

Stable, light load.

  1. Rebooted?
uptime -s

Output:

2026-10-27 02:13:44

It restarted at 2:13 AM: find out why.

  1. Overloaded?
uptime; nproc

Output:

load average: 9.80, 8.40, 6.10
4

Load 9.8 on 4 CPUs: work is queuing.

  1. Pretty.
uptime -p

Output:

up 6 weeks, 2 days, 3 hours

Easy for a report.

Practise this in the tasks below: Practice tasks

Real use: A Kothrud clinic chain checks uptime -s every morning to catch silent power-cut reboots of its billing box.

7. useradd: Create a user

useradd in depth: create users

A new developer joins, or an app needs its own service account. Create it properly with a home, shell and groups.

useradd creates an account. -m makes the home folder, -s sets the shell, -G adds extra groups, -c a comment, -u a UID, -r a system account, -e an expiry date. Then set a password with passwd or add an SSH key.

Common options

OptionWhat it does
-mMake home.
-s /bin/bashShell.
-G wheel,devsExtra groups.
-r -s /sbin/nologinService account.
-e 2026-12-31Expiry.
-c "Name"Full name.
  1. A developer.
sudo useradd -m -s /bin/bash -G devs -c "Sneha Patil" sneha; id sneha

Output:

uid=1005(sneha) gid=1005(sneha) groups=1005(sneha),1002(devs)

Home, shell and group ready.

  1. Set a first password.
sudo passwd sneha

Output:

passwd: all authentication tokens updated successfully.

She can log in.

  1. A service account.
sudo useradd -r -s /sbin/nologin -d /srv/billing billing

No login shell: safer.

  1. A contractor with expiry.
sudo useradd -m -e 2026-12-31 vendor1; sudo chage -l vendor1 | grep "Account expires"

Output:

Account expires						: Dec 31, 2026

Locks itself at year end.

Practise this in the tasks below: Practice tasks

Real use: A Wakad IT services firm creates every contractor with useradd -e so access ends with the contract.

8. userdel: Delete a user

userdel in depth: remove users

When someone leaves, their account must go, but their files may be needed for audit. Decide first, then remove.

userdel removes an account. -r also removes the home folder and mail spool. It refuses if the user is logged in; -f forces. Files elsewhere stay with a bare UID owner; find them with find / -nouser. Locking (usermod -L) is often safer first.

Common options

OptionWhat it does
userdel userRemove account.
-rAnd home.
-fForce.
find / -nouserOrphan files.
usermod -LLock instead.
  1. Back up the home.
sudo tar czf /backup/amit-home.tgz /home/amit

Kept for audit.

  1. Remove with home.
sudo userdel -r amit

Account and home gone.

  1. Still logged in.
sudo userdel -r rahul

Output:

userdel: user rahul is currently used by process 4410

End the session first.

  1. Find leftovers.
sudo find / -xdev -nouser 2>/dev/null | head -2

Output:

/srv/reports/q3.xlsx
/tmp/amit-test

Give these to a new owner.

Practise this in the tasks below: Practice tasks

Real use: A Viman Nagar BPO backs up the home folder, then runs userdel -r on the agent's last day.

9. usermod: Change a user

usermod in depth: change users

Someone moves to the DevOps team, needs docker access, changes name or goes on long leave. usermod changes an existing account.

usermod -aG adds groups (always use -a with -G, or other groups are removed). -L locks, -U unlocks, -s changes the shell, -d -m moves the home, -l renames, -e sets expiry. Group changes apply at next login.

Common options

OptionWhat it does
-aG docker userAdd a group.
-L / -ULock / unlock.
-s /sbin/nologinNo login.
-l new oldRename.
-e 2026-11-30Expiry.
  1. Give docker access.
sudo usermod -aG docker sneha; id -nG sneha

Output:

sneha devs docker

Works after she logs in again.

  1. The -a mistake.
sudo usermod -G docker raj; id -nG raj

Output:

raj docker

devs was removed: always use -aG.

  1. Lock during leave.
sudo usermod -L priya; sudo passwd -S priya

Output:

priya LK 2026-10-27 0 99999 7 -1 (Password locked.)

Locked, files untouched.

  1. Unlock on return.
sudo usermod -U priya

Access back.

Practise this in the tasks below: Practice tasks

Real use: A Magarpatta fintech locks accounts with usermod -L for employees on sabbatical and unlocks them on return.

10. vgcreate: Create an LVM volume group

vgcreate in depth: build an LVM volume group

You want one big flexible storage pool from several disks, so volumes can grow later without downtime. That pool is a volume group.

vgcreate makes a volume group from physical volumes (pvcreate, Part 5). vgs and vgdisplay show it, vgextend adds a disk, vgreduce removes one. Then lvcreate (Part 4) carves logical volumes from it.

Common options

OptionWhat it does
vgcreate vg pv...Create.
vgsSummary.
vgdisplay vgDetail.
vgextend vg pvAdd a disk.
vgreduce vg pvRemove a disk.
  1. Prepare disks.
sudo pvcreate /dev/xvdf /dev/xvdg

Output:

  Physical volume "/dev/xvdf" successfully created.
  Physical volume "/dev/xvdg" successfully created.

Two PVs.

  1. Create the group.
sudo vgcreate vgdata /dev/xvdf /dev/xvdg

Output:

  Volume group "vgdata" successfully created

A 200 GB pool.

  1. Check it.
sudo vgs

Output:

  VG     #PV #LV #SN Attr   VSize   VFree
  vgdata   2   0   0 wz--n- 199.99g 199.99g

All free for volumes.

  1. Grow it later.
sudo pvcreate /dev/xvdh && sudo vgextend vgdata /dev/xvdh

Output:

  Volume group "vgdata" successfully extended

300 GB, no downtime.

Practise this in the tasks below: Practice tasks

Real use: A Hinjewadi analytics firm builds vgdata from three EBS disks and grows it each quarter as data arrives.

11. vim: Edit files in the terminal

vim in depth: edit files on any server

Many Linux servers have vi or vim without a GUI. A minimal installation can omit them. You must be able to open a config, change a line, save and quit.

vim has modes. Normal mode moves and edits (dd delete line, yy copy, p paste, u undo, /text search, gg top, G bottom). i enters Insert mode, Esc returns. Commands start with : like :w save, :q quit, :wq save and quit, :q! quit without saving, :%s/a/b/g replace, :set number.

Common options

OptionWhat it does
i / EscInsert / normal.
:wqSave and quit.
:q!Quit, discard.
dd / uDelete line / undo.
/textSearch.
:%s/a/b/gReplace all.
+42Open at line 42.
  1. Open at an error line.
vim +42 /etc/nginx/nginx.conf

Output:

(cursor on line 42)

Straight to the problem.

  1. Change and save.
i ... Esc :wq

Output:

"/etc/nginx/nginx.conf" 88L, 2410B written

Saved.

  1. Replace a port everywhere.
:%s/8080/9090/g

Output:

3 substitutions on 3 lines

All three changed.

  1. Read-only file.
:w

Output:

E45: 'readonly' option is set (add ! to override)

Open with sudo instead.

Practise this in the tasks below: Practice tasks

Real use: A Deccan college lab teaches vim in the first Linux session because every exam server has no GUI.

12. vmstat: Memory, CPU and I/O summary

vmstat in depth: memory, CPU and IO over time

top shows a moment; vmstat shows a trend every few seconds, so you see swapping, IO wait or CPU queues build up.

vmstat DELAY COUNT prints rows: r runnable processes, b blocked, swpd and free memory, si/so swap in/out, bi/bo block IO, us sy id wa st CPU. The first row is the average since boot. -S M shows megabytes, -w wide.

Common options

OptionWhat it does
vmstat 2 55 rows, 2 s apart.
-S MMegabytes.
-wWide.
si / soSwap in / out.
r / bRun queue / blocked.
  1. Watch for 10 seconds.
vmstat -S M 2 5

Output:

procs ---memory--- --swap-- ---io--- ----cpu----
 r  b swpd free  si  so  bi  bo us sy id wa st
 1  0    0  812   0   0  10  40  8  2 89  1  0

Healthy: low wa, no swapping.

  1. Memory pressure.
vmstat 2 3 | tail -1

Output:

 3  2 1024  60 450 620  900 1200 20 10 30 40  0

High si/so: the box is swapping.

  1. CPU queue.
vmstat 1 3 | tail -1

Output:

 14  0 0 2000 0 0 0 5 95 5 0 0 0

14 waiting on 4 CPUs: add CPU or fix the hot loop.

  1. Log a trend.
vmstat -t 60 60 > vm-hour.log

One hour, timestamped.

Practise this in the tasks below: Practice tasks

Real use: A Pimpri ERP vendor runs vmstat 60 during month-end close to prove whether the slowdown is RAM or disk.

13. w: Who is logged in and what they do

w in depth: who is on and what they run

Before a reboot, check who is logged in and what they are doing, so you do not cut a colleague's migration.

w shows uptime and load like uptime, then one row per session: user, TTY, from where, login time, idle time and current command. -h hides the header, -s short format. who gives less detail; last shows history.

Common options

OptionWhat it does
wAll sessions.
w userOne user.
-hNo header.
-sShort.
wall "msg"Message all.
  1. Before a reboot.
w

Output:

11:55:02 up 41 days,  2 users,  load average: 0.30, 0.25, 0.20
USER  TTY   FROM        LOGIN@  IDLE  WHAT
ravi  pts/0 10.0.0.12   11:40   0.00s w
meena pts/1 10.0.0.31   10:02   2.00s psql billing

Meena is in psql: ask first.

  1. One user.
w -h meena

Output:

meena pts/1 10.0.0.31 10:02 2.00s psql billing

Same row, no header.

  1. Warn everyone.
sudo wall "Reboot at 12:30 for kernel patch"

Output:

Broadcast message from ravi@web01 (pts/0): Reboot at 12:30 for kernel patch

Everyone sees it.

  1. Idle sessions.
w -h | awk "\$5 ~ /days/"

Output:

test pts/3 10.0.0.9 Mon10 3days -bash

A forgotten session.

Practise this in the tasks below: Practice tasks

Real use: A Swargate transport office runs w before every patch window so no dispatcher session is cut.

14. watch: Run a command again and again

watch in depth: repeat a command and see changes

Waiting for a pod to become Ready, a disk to fill or a queue to drain? watch reruns the command every few seconds.

watch runs a command every 2 seconds full screen. -n sets the interval, -d highlights differences, -t hides the header, -g exits when output changes, -e exits on error. Quote commands with pipes.

Common options

OptionWhat it does
-n 5Every 5 s.
-dHighlight changes.
-tNo header.
-gStop on change.
"a | b"Quote pipes.
  1. Watch disk.
watch -n 5 df -h /data

Output:

Every 5.0s: df -h /data
/dev/xvdf  100G  71G  29G  71% /data

Updates live during the copy.

  1. Highlight changes.
watch -d "ss -tn state established | wc -l"

Output:

143

Connection count changes are highlighted.

  1. Stop when done.
watch -g -n 10 "kubectl get pod api-0 | tail -1"

Output:

api-0  1/1  Running

Exits once the pod changes state.

  1. Queue drain.
watch -n 30 "redis-cli llen jobs"

Output:

(integer) 1240

Count falls as workers finish.

Practise this in the tasks below: Practice tasks

Real use: A Hadapsar fulfilment centre keeps watch -n 30 on the order queue during flash sales.

15. wc: Count lines, words, bytes

wc in depth: count lines, words and bytes

How many errors today? How many users in the CSV? How big is the payload? wc counts.

wc prints lines, words and bytes. -l lines only, -w words, -c bytes, -m characters (multi-byte aware), -L longest line. With many files it adds a total. Reading from a pipe prints only the number.

Common options

OptionWhat it does
-lLines.
-wWords.
-cBytes.
-mCharacters.
-LLongest line.
  1. Count errors.
grep -c ERROR app.log; grep ERROR app.log | wc -l

Output:

57
57

Same result two ways.

  1. Rows in a CSV.
wc -l users.csv

Output:

1001 users.csv

1000 users plus a header.

  1. Many files.
wc -l *.log

Output:

  120 api.log
  340 web.log
  460 total

Total at the end.

  1. Marathi text.
echo "पुणे" | wc -c; echo "पुणे" | wc -m

Output:

13
5

Bytes and characters differ for Devanagari.

Practise this in the tasks below: Practice tasks

Real use: A Shaniwar Peth publisher checks wc -w on every Marathi article to stay within the print word limit.

16. whereis: Find binary, source and man page

whereis in depth: binary, source and man page

Is a tool installed at all, and where is its man page? whereis searches standard system folders.

whereis lists the binary, source and manual files for a name from standard locations, not your PATH. -b binaries only, -m man pages only, -s sources. It does not see aliases or functions; use type for that.

Common options

OptionWhat it does
whereis nameAll.
-bBinaries.
-mMan pages.
-sSources.
  1. Find a tool.
whereis nginx

Output:

nginx: /usr/sbin/nginx /usr/share/nginx /usr/share/man/man8/nginx.8.gz

Binary and man page.

  1. Not installed.
whereis htop

Output:

htop:

Nothing found: install it.

  1. Man page only.
whereis -m crontab

Output:

crontab: /usr/share/man/man1/crontab.1.gz /usr/share/man/man5/crontab.5.gz

Two sections exist.

  1. Binary only.
whereis -b python3

Output:

python3: /usr/bin/python3 /usr/local/bin/python3

Two copies on disk.

Practise this in the tasks below: Practice tasks

Real use: A Chinchwad support desk asks customers for whereis output to confirm their agent package installed.

17. which: Show the path of a command

which in depth: the file PATH will run

Two Java versions are installed and the wrong one runs. which shows the first match on PATH.

which prints the full path of the command that PATH resolves first. -a shows all matches. It is an external program, so it may miss aliases and functions; type and command -v are more exact in scripts.

Common options

OptionWhat it does
which nameFirst match.
-aAll matches.
command -vBuiltin check.
echo $PATHSearch order.
  1. Which java?
which java

Output:

/usr/bin/java

The system Java runs.

  1. All of them.
which -a java

Output:

/usr/bin/java
/opt/jdk-21/bin/java

JDK 21 is later on PATH.

  1. Fix PATH.
export PATH=/opt/jdk-21/bin:$PATH; which java

Output:

/opt/jdk-21/bin/java

Now JDK 21 wins.

  1. Script check.
command -v docker >/dev/null || echo "install docker"

Output:

install docker

Missing tool detected.

Practise this in the tasks below: Practice tasks

Real use: A Baner fintech CI image prints which -a java at start so build logs show the JDK used.

18. who: Show logged-in users

who in depth: logged-in users and boot

Quick check: who is logged in, from where, and when did the system boot?

who lists logged-in sessions with terminal, login time and source. -b last boot time, -r run level, -q names and count, -H headers. who am i shows your own session. w adds what each user runs.

Common options

OptionWhat it does
whoSessions.
-bBoot time.
-qNames and count.
-HHeaders.
who am iMy session.
  1. Who is on?
who

Output:

ravi   pts/0  2026-10-27 11:40 (10.0.0.12)
meena  pts/1  2026-10-27 10:02 (10.0.0.31)

Two people.

  1. Last boot.
who -b

Output:

         system boot  2026-09-16 08:31

Up since mid-September.

  1. Count.
who -q

Output:

ravi meena
# users=2

Two sessions.

  1. My session.
who am i

Output:

ravi  pts/0  2026-10-27 11:40 (10.0.0.12)

Your IP shows.

Practise this in the tasks below: Practice tasks

Real use: A Kalyani Nagar hotel IT team logs who -q hourly to spot logins outside the night-audit window.

19. whoami: Print your user name

whoami in depth: which user am I

After sudo, su or inside a container, it is easy to forget which user you are. Scripts also need to refuse to run as root, or insist on it.

whoami prints the effective user name. id -un is the same; id shows UID, groups too. In scripts compare $(id -u) with 0 to detect root.

Common options

OptionWhat it does
whoamiUser name.
id -unSame.
id -uUID.
idFull identity.
  1. Who am I?
whoami

Output:

ravi

Your own user.

  1. With sudo.
sudo whoami

Output:

root

Commands run as root.

  1. Root guard.
[ "$(id -u)" -eq 0 ] || { echo "run as root"; exit 1; }

Output:

run as root

Script stops early.

  1. In a container.
docker run --rm alpine whoami

Output:

root

Containers often default to root: set USER.

Practise this in the tasks below: Practice tasks

Real use: A Kharadi security team flags any Dockerfile whose image prints root for whoami.

20. xargs: Build commands from input

xargs in depth: turn lines into arguments

find gives a list of files and you want to delete, compress or copy each. xargs feeds the list to a command, in batches or in parallel.

xargs reads items from stdin and runs a command with them as arguments. -0 pairs with find -print0 for safe names with spaces, -n sets items per run, -P runs in parallel, -I {} places the item anywhere, -r skips running on empty input, -t prints each command.

Common options

OptionWhat it does
-0Null separated.
-n 1One per run.
-P 44 in parallel.
-I {}Placeholder.
-rSkip if empty.
-tShow commands.
  1. Compress old logs.
find /var/log/app -name "*.log" -mtime +7 -print0 | xargs -0 -r gzip -v

Output:

api-2026-10-12.log:  88.1% -- replaced with api-2026-10-12.log.gz

Safe with spaces, nothing runs if empty.

  1. Parallel pings.
cat hosts.txt | xargs -P 8 -I {} ping -c1 -W1 {}

Output:

64 bytes from 10.0.1.5: icmp_seq=1 ttl=64 time=0.4 ms

Eight at a time.

  1. Placeholder.
ls *.csv | xargs -I {} cp {} /backup/{}.bak

Each file copied with a new name.

  1. See what runs.
echo a b c | xargs -n 1 -t echo

Output:

echo a
a
echo b
b
echo c
c

One run per item.

Practise this in the tasks below: Practice tasks

Real use: A Bhosari CNC workshop uses find -print0 | xargs -0 -P 4 to convert the day's machine logs to CSV.

21. xz: Compress files with xz

xz in depth: strongest common compression

Archiving a year of logs or shipping a big release, you want the smallest file and do not mind waiting longer. xz gives that.

xz compresses a file to .xz and removes the original; -d or unxz decompresses, -k keeps the original, -0 to -9 sets level, -T0 uses all CPUs, -l lists ratio, xzcat reads without extracting. tar cJf makes .tar.xz. Detailed comparison is in the compression chapter.

Common options

OptionWhat it does
xz fileCompress.
-dDecompress.
-kKeep original.
-9 -T0Max, all CPUs.
-lInfo.
xzcatRead.
  1. Compress, keep original.
xz -k -T0 audit-2025.log; ls -lh audit-2025.log*

Output:

-rw-r--r-- 1 ravi ravi 2.1G audit-2025.log
-rw-r--r-- 1 ravi ravi  96M audit-2025.log.xz

About 22 times smaller.

  1. Ratio.
xz -l audit-2025.log.xz | tail -1

Output:

    1       1     95.8 MiB  2,048.0 MiB  0.047  CRC64  audit-2025.log.xz

4.7% of the original.

  1. Read without extracting.
xzcat audit-2025.log.xz | grep -c "login failed"

Output:

3120

Search a compressed archive.

  1. Tar with xz.
tar cJf release-4.2.tar.xz release/

Smallest release download.

Practise this in the tasks below: Practice tasks

Real use: A Shivajinagar government office keeps seven years of audit logs as .xz to fit its storage budget.

22. yes: Print a line again and again

yes in depth: repeat an answer or make load

An old installer keeps asking "Continue? [y/N]". yes answers for you. It can also make quick test data or CPU load.

yes prints y (or any text you give) forever until stopped. Pipe it into a prompting command, cut it with head -n for N lines, or run it to load one CPU core. Prefer a tool's own -y flag when it has one.

Common options

OptionWhat it does
yesPrint y forever.
yes textRepeat text.
| head -n 5Limit.
yes > /dev/null &CPU load.
-y flagPrefer the tool flag.
  1. Answer prompts.
yes | ./legacy-install.sh | tail -1

Output:

Install complete.

Every prompt got y.

  1. Test lines.
yes "order,Pune,100" | head -n 3

Output:

order,Pune,100
order,Pune,100
order,Pune,100

Quick test data.

  1. Load a CPU.
yes > /dev/null & top -b -n 1 | grep yes

Output:

4512 ravi 20 0 8.3m 1.8m R 99.7 0.0 yes

One core at 100% to test alerts.

  1. Stop it.
kill %1

Output:

[1]+  Terminated  yes > /dev/null

Load gone.

Practise this in the tasks below: Practice tasks

Real use: A Kharadi monitoring team runs yes > /dev/null on a test box to check that CPU alerts reach the on-call phone.

23. yum: Old package tool on RHEL and CentOS

yum in depth: packages on older Red Hat systems

Amazon Linux 2, CentOS 7 and RHEL 7 still run many production servers. Their package tool is yum; on newer systems yum is an alias for dnf.

yum install, remove, update and search manage RPM packages with dependencies; info shows details, list installed lists them, provides finds which package owns a file, history shows and undoes transactions, -y answers yes. Same commands as dnf (Part 2).

Common options

OptionWhat it does
install -y pkgInstall.
remove pkgRemove.
updateUpdate all.
search wordSearch.
provides */fileWho owns a file.
history undo NRoll back.
  1. Install.
sudo yum install -y httpd

Output:

Installed:
  httpd-2.4.62-1.amzn2.x86_64
Complete!

Apache installed.

  1. Which package has a file?
yum provides "*/bin/dig"

Output:

bind-utils-9.11.4-26.P2.amzn2.13.x86_64 : Utilities for querying DNS name servers

Install bind-utils for dig.

  1. History.
sudo yum history | head -4

Output:

ID | Command line   | Date and time    | Action(s)
 42 | update         | 2026-10-27 02:00 | Update

Last night's update is 42.

  1. Undo it.
sudo yum history undo 42 -y

Output:

Complete!

Packages back to before.

Practise this in the tasks below: Practice tasks

Real use: A Hinjewadi insurance firm still patches its Amazon Linux 2 claim servers with yum update during the Sunday window.

24. zcat: Read .gz files without unpacking

zcat in depth: read gzip files without extracting

Rotated logs are .gz. To search last week's errors you do not want to extract gigabytes to disk first.

zcat prints the decompressed content of .gz files to stdout and leaves them compressed. zgrep searches, zless pages, zdiff compares. -f also passes plain files through. xzcat and bzcat do the same for .xz and .bz2.

Common options

OptionWhat it does
zcat f.gzPrint.
zgrep pat f.gzSearch.
zless f.gzPage.
zcat -f *Plain too.
xzcat / bzcatOther formats.
  1. Read a rotated log.
zcat /var/log/messages-20261020.gz | head -1

Output:

Oct 14 00:00:01 web01 systemd[1]: Started Daily rotation of log files.

No extraction needed.

  1. Count errors in a week.
zcat app.log.*.gz | grep -c ERROR

Output:

812

Across all rotated files.

  1. Search directly.
zgrep -h "order 5512" app.log.3.gz

Output:

2026-10-24 18:02:11 order 5512 payment timeout

Found the old incident.

  1. Mixed files.
zcat -f app.log app.log.1.gz | wc -l

Output:

91240

Plain and gzip together.

Practise this in the tasks below: Practice tasks

Real use: A Viman Nagar airline ops team uses zgrep to trace a passenger complaint through two weeks of compressed booking logs.

25. Commands in this range already covered in depth

These commands already have a full why, what and how section in an earlier chapter. Repeating them here would only make the page longer.

Each link opens the exact section with options, examples and output.

  • unzip: Extract zip files: -l, -d, -o and -q
  • wget: Download files: -O, -c, -q and --mirror
  • zip: Create zip files: -r, -e, -x and -9

26. Real examples from many industries

The same Linux skill shows up in every kind of company. Seeing it in many places helps you remember it.

Each row is a made-up team. It shows who uses this and how.

Team and cityHow they use itCommand
Neha, telecom, MagarpattaCounts call failuressort | uniq -c
Sagar, bank IT, BanerOnboards usersuseradd -m -G finance
Meera, pharma, BhosariWatches batch serversvmstat 5
Vikram, logistics, ChakanGrows storagevgcreate vgdata /dev/xvdf
Pooja, edtech, AundhBulk renames filesfind . -name "*.tmp" | xargs rm
Nikhil, media, Koregaon ParkArchives logsxz -T0 big.log

27. Common errors and how to fix them

Everyone hits these errors. Knowing the cause saves hours.

Read the exact message first. Then match it to a row below.

Error you seeWhy it happensHow to fix
useradd: user 'ravi' already existsName takenUse usermod or pick another name.
id ravi
usermod: user ravi is currently used by process 2211User is logged inAsk them to log out or stop the process.
pkill -u ravi
userdel: user ravi is currently used by process 2211User still running processesStop processes then delete.
sudo pkill -u ravi; sudo userdel -r ravi
usermod: group 'dockr' does not existTypo in group nameCheck with getent group.
getent group docker
Device /dev/xvdf excluded by a filter.Disk has old signaturesCheck with wipefs; clean only if sure.
sudo wipefs /dev/xvdf
E212: Can't open file for writingNo permission in vimSave with sudo tee.
:w !sudo tee % > /dev/null
E325: ATTENTION Found a swap fileAnother vim open or crashedRecover or delete the .swp.
vim -r file
xargs: unmatched single quote; by default quotes are special to xargs unless you use the -0 optionFilename with quoteUse find -print0 with xargs -0.
find . -print0 | xargs -0 ls
xz: file.xz: File format not recognizedNot an xz fileCheck with file.
file file.xz
gzip: stdin: not in gzip formatzcat on non-gzip fileUse xzcat or cat.
file app.log.1
Error: Unable to find a match: htoppPackage name wrongSearch the name.
yum search htop
which: no kubectl in (/usr/local/bin:/usr/bin)Not installed or not in PATHInstall it or fix PATH.
echo $PATH

28. Troubleshooting step by step

When a Part 8 command does not do what you expect, go through these steps.

Go top to bottom. Stop at the first step that shows the problem.

  1. Is the input sorted?
sort file | uniq -c
  1. Does the user exist?
id ravi; getent passwd ravi
  1. Is it installed?
which tool; rpm -q tool
  1. What file type is it?
file archive
  1. Names with spaces?
find . -print0 | xargs -0 echo
  1. Is the box overloaded?
uptime; vmstat 1 5

29. Lab 1: Onboard and offboard a user

After changing the test user’s groups, start a new session and run id there. An old shell can still have the group list it received at login. Verify that the intended lab member can read the shared file. When offboarding, review the sample user’s files and retest access for the remaining group. The account change is only one part of the result.

Create a user with a group, check it, lock it, then remove it with its home.

A full hands-on lab. Run every step on a test Linux machine (an EC2 instance, a VM, or WSL).

  1. Create.
sudo groupadd labteam; sudo useradd -m -G labteam -s /bin/bash labuser
  1. Check.
id labuser

Output:

uid=1005(labuser) gid=1005(labuser) groups=1005(labuser),1006(labteam)
  1. Lock.
sudo usermod -L labuser; sudo passwd -S labuser

Output:

labuser LK
  1. Remove.
sudo userdel -r labuser; sudo groupdel labteam; id labuser

Output:

id: labuser: no such user

30. Lab 2: Compress, count and watch logs

Check the compressed sample without losing the original. Read it through the decompression tool, count and compare one known record with the plain file. Check the disk size separately. A smaller file tells you the bytes were compressed. The count and record checks tell you whether the reader in your workflow can still access the data.

Make a test log, compress it with xz, count it with xzcat and wc, and watch its size.

A full hands-on lab. Run every step on a test Linux machine (an EC2 instance, a VM, or WSL).

  1. Make a log.
yes "GET /api 200" | head -n 100000 > /tmp/t.log; wc -l /tmp/t.log

Output:

100000 /tmp/t.log
  1. Compress.
xz -k /tmp/t.log; ls -lh /tmp/t.log*
  1. Count.
xzcat /tmp/t.log.xz | uniq -c

Output:

100000 GET /api 200
  1. Watch.
watch -n 2 ls -lh /tmp/t.log.xz
  1. Clean.
rm /tmp/t.log /tmp/t.log.xz

Ravindra Bagale's Tip

Always sort before uniq, test xargs with echo first, and never userdel -r before you back up the home folder. Small checks save big mistakes.

31. Frequently asked questions

Q. Why does uniq miss duplicates?

It only joins neighbouring lines; sort first.

Q. yum or dnf?

On new RHEL and Amazon Linux 2023, yum points to dnf.

Q. w or who?

w also shows load and what each user runs.

Q. xz or gzip?

xz is smaller but slower; gzip is faster.

Q. How do I quit vim?

Esc then :q! to quit without saving or :wq to save.

Q. usermod -G or -aG?

-aG adds; -G alone replaces all groups.

32. Interview questions and answers

Beginner level

Q. Count lines in a file?

wc -l file.

Q. Who am I?

whoami.

Q. Install a package?

sudo yum install name.

Q. System uptime?

uptime.

Mid level level

Q. Top 5 repeated lines?

sort | uniq -c | sort -rn | head -5.

Q. Add a user to docker group safely?

usermod -aG docker user.

Q. Delete many files safely?

find -print0 | xargs -0 rm.

Q. Read a .gz log without unzipping?

zcat or zgrep.

Senior level

Q. Box is slow; uptime shows load 20. Steps?

vmstat for r, b and wa, top, then disk or CPU owner.

Q. Design user offboarding.

Lock, kill sessions, archive home with tar, userdel -r, audit sudoers.

Q. Add 500 GB to a full LVM volume.

pvcreate, vgextend, lvextend -r.

Q. Logs eat disk. Plan?

logrotate with compress, xz old, zcat to read, watch df.

Try at home

  1. Find the top 10 words in a text file using tr, sort, uniq and wc.
  2. Create two users in one group and remove them.
  3. Run vmstat 2 10 while a tar backup runs and note wa.
  4. Compress a log with gzip and xz and compare sizes.

Practise this chapter

Interview questions and answers

You added a test user to a shared group but a terminal still cannot access the folder. What would you verify?

Check saved group membership and the groups of the actual running session. Open a fresh lab login and use id there before retesting access. Also inspect the folder’s group and traversal mode. The stored account setting and a process’s active credentials can differ.

Check your understanding

Choose an answer, then compare your reasoning with the explanation.

0 of 3 answered correctly
1. What does uniq -c count in the input web, db, web in that order?

Answer and explanation

A. Three runs, each of length one

uniq combines adjacent equal lines. A separated repetition forms a new run.

2. Which check shows the new group list used by a fresh test login?

Answer and explanation

C. Run id in that login

id reports process identity and active groups where it runs. An older shell can hold older credentials.

3. What should you compare when checking a compressed practice log?

Answer and explanation

C. Known records and count after reading it, in addition to its stored size

Stored size measures compression. Successful reads and matching data prove your tooling can use the output.

Practice Tasks

Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.

About this scenario

Vidarbha Cotton Mills is a textiles business in Nagpur. Ganesh Wankhede looks after its IT and cloud work. They count money in INR and run their AWS resources in the ap-south-1 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 20

Easy Open at a line

BIZ runs Linux servers and uses commands from uniq to zip daily.

Open nginx.conf in vim with the cursor at line 40.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Count words

BIZ runs Linux servers and uses commands from uniq to zip daily.

Count the words in essay.txt.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Find a binary

BIZ runs Linux servers and uses commands from uniq to zip daily.

Show the full path of the python3 command from PATH.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Binary and man page

BIZ runs Linux servers and uses commands from uniq to zip daily.

Show where the binary and manual for rsync live.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Install package

BIZ runs Linux servers and uses commands from uniq to zip daily.

Install the package tcpdump without asking for confirmation.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Read gz

BIZ runs Linux servers and uses commands from uniq to zip daily.

Print the contents of audit.1.gz without unzipping it to disk.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Three yes lines

BIZ runs Linux servers and uses commands from uniq to zip daily.

Print the word agree exactly 3 times using yes.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Count lines

BIZ runs Linux servers and uses commands from uniq to zip daily.

Count the lines in vendors.csv.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Count repeats

BIZ runs Linux servers and uses commands from uniq to zip daily.

Count how many times each line appears in cities.txt (sort first).

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Only duplicates

BIZ runs Linux servers and uses commands from uniq to zip daily.

Show only lines that repeat in sorted skus.txt.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Create user with home

BIZ runs Linux servers and uses commands from uniq to zip daily.

Create the user farhan with a home folder.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Delete user and home

BIZ runs Linux servers and uses commands from uniq to zip daily.

Delete the user oldintern and the home folder.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Add to group

BIZ runs Linux servers and uses commands from uniq to zip daily.

Add the user sneha to the group auditors without removing other groups.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Change shell

BIZ runs Linux servers and uses commands from uniq to zip daily.

Change the login shell of the user ftpbot to /sbin/nologin.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium vmstat samples

BIZ runs Linux servers and uses commands from uniq to zip daily.

Print vmstat every 3 seconds, 4 times.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Watch memory

BIZ runs Linux servers and uses commands from uniq to zip daily.

Run free -m every 4 seconds with watch.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Decompress xz

BIZ runs Linux servers and uses commands from uniq to zip daily.

Decompress scans.tar.xz but keep the .xz file.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Search gz

BIZ runs Linux servers and uses commands from uniq to zip daily.

Search for ERROR inside app.3.gz without unzipping.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Hard Make a volume group

BIZ runs Linux servers and uses commands from uniq to zip daily.

Create the volume group vgmedia from /dev/nvme2n1.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Hard Safe xargs delete

BIZ runs Linux servers and uses commands from uniq to zip daily.

Find files ending in .part under /dl and remove them safely with xargs, even with spaces.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

In short

  1. uniq, wc, xargs: count and batch.
  2. uptime, w, who, vmstat, watch: load and people.
  3. useradd, usermod, userdel: users.
  4. vgcreate: storage.
  5. vim, which, whereis, whoami: tools.
  6. xz, zcat, yes, yum: packages and archives.

Revision, comparison and interview cards

Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.

Manage users in 4 steps. Create with home. Add a group. Check. Remove with home.
Revision card: Manage users in 4 steps · Download PNG · Open card page
Count data fast. Count lines. Count repeats. Only duplicates. Read gz logs.
Revision card: Count data fast · Download PNG · Open card page
xz vs gzip. Smallest files. / Faster.
Comparison: xz vs gzip · Download PNG · Open card page
w vs who. Users plus load and command. / Just users and login time.
Comparison: w vs who · Download PNG · Open card page
uniq misses duplicates?. It joins only neighbours. Sort first. Or sort -u.
Interview card: uniq misses duplicates? · Download PNG · Open card page
User lost all groups?. -G alone replaces groups. Use -aG. Verify.
Interview card: User lost all groups? · Download PNG · Open card page
Delete files with spaces safely?. Use null separators. Test with echo first. Or find -delete.
Interview card: Delete files with spaces safely? · Download PNG · Open card page
Server slow: CPU or disk?. Sample vmstat. High wa means disk. High us means CPU.
Interview card: Server slow: CPU or disk? · Download PNG · Open card page

More cards: Ravi Sir's Cards.