> ## Documentation Index
> Fetch the complete documentation index at: https://notes.vvkhash.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Linux Essentials: Commands Every Engineer Must Know

> Core Linux commands for filesystem navigation, text processing, process management, and system inspection — a daily-use reference for working engineers.

Linux mastery is built on muscle memory. After 25+ years working with RHEL, CentOS, Fedora, Ubuntu, Debian, and FreeBSD systems, the commands below are the ones I reach for every single day. This page is deliberately dense — it is a reference, not a tutorial. If a flag or idiom looks unfamiliar, run `man <command>` to dig deeper.

***

## Filesystem Navigation

<CodeGroup>
  ```bash ls variants theme={null}
  ls -la               # long listing including hidden files
  ls -lh               # human-readable sizes (K, M, G)
  ls -lt               # sort by modification time, newest first
  ls -lS               # sort by file size, largest first
  ls --color=auto -F   # colorized + type indicator (/, *, @)
  ```

  ```bash find essentials theme={null}
  # Find by name (case-insensitive)
  find /etc -iname "*.conf" -type f

  # Find files modified in the last 24 hours
  find /var/log -mtime -1 -type f

  # Find files larger than 100 MB
  find / -size +100M -type f 2>/dev/null

  # Find and execute on results
  find /tmp -name "*.tmp" -exec rm -f {} \;

  # Find SUID binaries (security audit)
  find / -perm -4000 -type f 2>/dev/null
  ```

  ```bash locate / pwd / cd theme={null}
  pwd                  # print current working directory
  cd -                 # jump back to previous directory
  cd ~username         # jump to another user's home

  # locate uses a prebuilt index — fast but not real-time
  locate nginx.conf
  sudo updatedb        # refresh the locate database
  ```
</CodeGroup>

<Tip>
  Use `find` when you need real-time results or complex filters. Use `locate` when you want speed and the file hasn't changed recently. Run `sudo updatedb` in a cron job nightly to keep the index fresh.
</Tip>

***

## File Operations

<CodeGroup>
  ```bash copy / move / remove theme={null}
  cp -av /src /dst          # archive mode + verbose (preserves permissions/timestamps)
  cp -p file1 file2         # preserve mode, ownership, timestamps
  cp --backup=numbered f1 f2 # keep numbered backups of the destination

  mv -iv oldname newname    # interactive + verbose rename/move

  rm -rf /path/to/dir       # force-remove recursively (no confirmation — be careful)
  rm -i file                # prompt before each removal
  ```

  ```bash mkdir / chmod / chown theme={null}
  mkdir -p /opt/app/{bin,conf,logs,tmp}   # create nested dirs in one shot

  chmod 755 /opt/app/bin/start.sh         # rwxr-xr-x
  chmod -R 644 /var/www/html              # recursive on files
  chmod u+x,g-w script.sh                 # symbolic notation

  chown -R app:app /opt/app               # owner:group recursive
  chown --reference=ref.txt target.txt    # copy ownership from reference file
  ```

  ```bash symlinks theme={null}
  ln -s /opt/app/current/bin/app /usr/local/bin/app   # soft link
  ln    /data/file.dat /backup/file.dat                # hard link

  # Update an existing symlink atomically
  ln -sfn /opt/app/v2.1 /opt/app/current
  ```
</CodeGroup>

<Warning>
  `rm -rf` with a misplaced space or variable is catastrophic. Always double-check the path. Consider `trash-cli` on workstations, or at minimum `alias rm='rm -i'` in your `.bashrc`.
</Warning>

***

## Text Processing

This is where Linux really shines. Master these tools and you rarely need a dedicated log-analysis GUI.

<Tabs>
  <Tab title="grep">
    ```bash theme={null}
    grep -rn "ERROR" /var/log/app/        # recursive + line numbers
    grep -i "timeout" access.log          # case-insensitive
    grep -v "DEBUG" app.log               # invert match (exclude)
    grep -E "WARN|ERROR|CRIT" syslog      # extended regex (alternation)
    grep -A3 -B3 "OOM" /var/log/messages  # 3 lines of context around match
    grep -c "404" access.log              # count matching lines
    grep -l "pattern" /etc/**/*.conf      # list filenames only
    ```
  </Tab>

  <Tab title="awk">
    ```bash theme={null}
    # Print specific columns (tab/space-delimited)
    awk '{print $1, $4}' access.log

    # Sum a column
    awk '{sum += $5} END {print "Total:", sum}' report.txt

    # Filter rows by field value
    awk '$9 == "500"' access.log

    # Use custom field separator
    awk -F: '{print $1, $3}' /etc/passwd

    # Print lines between two patterns
    awk '/START/,/END/' logfile.txt
    ```
  </Tab>

  <Tab title="sed">
    ```bash theme={null}
    sed -i 's/oldstring/newstring/g' file.conf    # in-place replace
    sed -i.bak 's/foo/bar/g' file.conf            # with .bak backup
    sed -n '10,20p' bigfile.txt                   # print lines 10–20
    sed '/^#/d' config.conf                       # delete comment lines
    sed 's/[[:space:]]*$//' file.txt              # strip trailing whitespace
    ```
  </Tab>

  <Tab title="cut / sort / uniq / wc">
    ```bash theme={null}
    # cut — slice fields from delimited input
    cut -d: -f1,3 /etc/passwd           # fields 1 and 3
    cut -c1-80 wide.txt                 # first 80 characters per line

    # sort
    sort -k2 -n file.txt                # numeric sort on column 2
    sort -t, -k3 -rn data.csv           # CSV, col 3, reverse numeric
    sort -u names.txt                   # sort + deduplicate

    # uniq (input must be sorted first)
    sort ips.txt | uniq -c | sort -rn   # count occurrences, rank by frequency

    # wc
    wc -l file.txt                      # line count
    wc -w file.txt                      # word count
    ls /var/log/*.log | wc -l           # count log files

    # head / tail
    head -n 50 app.log                  # first 50 lines
    tail -n 100 app.log                 # last 100 lines
    tail -f /var/log/syslog             # follow in real time
    tail -F /var/log/app.log            # follow + reopen if rotated
    ```
  </Tab>
</Tabs>

***

## Process Management

<CodeGroup>
  ```bash Inspect processes theme={null}
  ps aux                        # all processes, BSD style
  ps -ef                        # all processes, POSIX style
  ps aux | grep nginx           # filter by name
  ps -o pid,ppid,cmd,%mem,%cpu --sort=-%cpu | head -20  # custom columns, sort by CPU

  top                           # live view (press M to sort by memory, P by CPU)
  htop                          # nicer UI; F5 for tree view, F6 to sort
  ```

  ```bash Control processes theme={null}
  kill -15 <pid>                # SIGTERM — graceful shutdown (default)
  kill -9  <pid>                # SIGKILL — force kill (last resort)
  killall -HUP nginx            # send SIGHUP (reload) to all nginx processes
  pkill -u www-data             # kill all processes owned by www-data

  nice -n 10 ./heavy-job.sh     # start with lower priority (range: -20 to 19)
  renice -n 15 -p <pid>         # change priority of running process
  ```

  ```bash Background jobs theme={null}
  nohup ./long-task.sh > /tmp/task.log 2>&1 &   # survive terminal logout
  disown -h %1                                    # detach job from shell

  # screen
  screen -S mysession           # start named session
  screen -ls                    # list sessions
  screen -r mysession           # reattach
  # Inside screen: Ctrl+A D to detach, Ctrl+A K to kill

  # tmux
  tmux new -s deploy            # new named session
  tmux ls                       # list sessions
  tmux attach -t deploy         # reattach
  # Inside tmux: Ctrl+B D to detach, Ctrl+B [ to scroll
  ```
</CodeGroup>

<Note>
  Prefer `kill -15` (SIGTERM) first — it gives the process a chance to flush buffers and clean up. Only escalate to `kill -9` (SIGKILL) if the process doesn't respond after a few seconds.
</Note>

***

## System Information

<CodeGroup>
  ```bash OS / hardware identity theme={null}
  uname -r            # kernel version
  uname -a            # full kernel info (arch, hostname, date)
  hostnamectl         # systemd-based hostname + OS info
  cat /etc/os-release # distribution name and version
  lscpu               # CPU topology, cores, threads, cache
  lsblk -f            # block devices + filesystem types + mount points
  lspci               # PCI devices (NICs, GPUs, controllers)
  lsusb               # USB devices
  dmidecode -t system # hardware/BIOS info (requires root)
  ```

  ```bash Uptime / load theme={null}
  uptime              # uptime + 1/5/15-min load averages
  w                   # who is logged in + their activity
  last reboot         # reboot history
  ```

  ```bash Disk and memory theme={null}
  df -hT              # disk usage, human-readable + filesystem type
  df -i               # inode usage (critical for many small files)
  du -sh /var/*       # size of each item under /var
  du -h --max-depth=2 /opt | sort -rh | head -20  # top disk consumers

  free -m             # memory in MB (total/used/free/cache/available)
  vmstat 2 5          # virtual memory stats, 5 samples every 2 seconds
  cat /proc/meminfo   # full memory details
  ```
</CodeGroup>

***

## Package Management Quick Reference

<Tabs>
  <Tab title="APT (Debian / Ubuntu)">
    ```bash theme={null}
    apt update                          # refresh package index
    apt upgrade                         # upgrade all packages
    apt install nginx                   # install a package
    apt remove nginx                    # remove (keep config)
    apt purge nginx                     # remove + purge config
    apt autoremove                      # remove orphaned dependencies
    apt search "web server"             # search by keyword
    apt show nginx                      # package details
    dpkg -l | grep nginx                # check if installed
    dpkg -L nginx                       # list installed files
    dpkg -S /usr/sbin/nginx             # which package owns a file
    ```
  </Tab>

  <Tab title="YUM / DNF (RHEL / CentOS / Fedora)">
    ```bash theme={null}
    dnf check-update                    # list available updates
    dnf upgrade                         # apply all updates
    dnf install httpd                   # install a package
    dnf remove httpd                    # uninstall
    dnf search "web server"             # search
    dnf info httpd                      # package details
    dnf history                         # transaction history
    dnf history undo last               # rollback last transaction

    rpm -qa | grep httpd                # list installed RPMs matching name
    rpm -ql httpd                       # files owned by package
    rpm -qf /usr/sbin/httpd             # which RPM owns a file
    ```
  </Tab>

  <Tab title="FreeBSD pkg">
    ```bash theme={null}
    pkg update                          # refresh index
    pkg upgrade                         # upgrade all
    pkg install nginx                   # install
    pkg delete nginx                    # remove
    pkg search nginx                    # search
    pkg info nginx                      # details
    pkg which /usr/local/sbin/nginx     # which package owns a file
    ```
  </Tab>
</Tabs>

***

## User and Group Management

<CodeGroup>
  ```bash Users theme={null}
  useradd -m -s /bin/bash -G wheel appuser    # create user with home + shell + group
  usermod -aG docker appuser                  # add to additional group
  usermod -L appuser                          # lock account
  usermod -U appuser                          # unlock account
  userdel -r appuser                          # delete user + home directory
  passwd appuser                              # set/change password
  chage -l appuser                            # show password expiry info
  chage -M 90 appuser                         # password expires in 90 days
  id appuser                                  # show UID, GID, groups
  ```

  ```bash Groups theme={null}
  groupadd developers                         # create group
  groupmod -n devs developers                 # rename group
  groupdel devs                               # delete group
  gpasswd -d appuser devs                     # remove user from group
  getent group docker                         # list members of a group
  ```

  ```bash sudo / su theme={null}
  su - appuser                                # switch user (full login shell)
  sudo -u appuser /opt/app/start.sh           # run as another user
  sudo -l                                     # list your sudo privileges
  visudo                                      # safely edit /etc/sudoers
  # Add line in sudoers for passwordless sudo:
  # appuser ALL=(ALL) NOPASSWD: /bin/systemctl restart app
  ```
</CodeGroup>

<Note>
  Never edit `/etc/sudoers` directly. Always use `visudo`, which validates syntax before saving. A broken sudoers file can lock you out of root access.
</Note>

***

## Related Pages

<CardGroup cols={2}>
  <Card title="Bash Scripting" icon="terminal" href="linux/bash-scripting">
    Turn these one-liners into reusable, robust shell scripts.
  </Card>

  <Card title="Networking" icon="network-wired" href="linux/networking">
    Network diagnostics, SSH, firewalls, and DNS troubleshooting.
  </Card>

  <Card title="Troubleshooting" icon="bug" href="linux/troubleshooting">
    Systematic workflows for CPU, memory, disk, and service issues.
  </Card>

  <Card title="DevOps Overview" icon="infinity" href="devops/overview">
    CI/CD, containers, and orchestration context for these commands.
  </Card>
</CardGroup>
