UNIX Shell Flashcards

(74 cards)

1
Q

What is Unix?

A

Unix is a family of multitasking - multiuser operating systems originally developed at Bell Labs in the 1960s-70s. Key characteristics: everything is a file + hierarchical file system + small modular programs that do one thing well + shell scripting + pipes for combining commands. Linux is a Unix-like OS (not Unix itself). macOS is Unix-certified. Foundation of modern computing including Android - macOS - cloud servers

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is Linux?

A

Linux is a free open-source Unix-like operating system kernel created by Linus Torvalds in 1991. The full OS (Linux kernel + GNU tools) is often called GNU/Linux. Distributions (distros): Ubuntu + CentOS/RHEL + Debian + Fedora + Alpine + Amazon Linux. Dominates: web servers + cloud + Android + embedded systems. Kernel is at the core - manages hardware - processes - memory - file system

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the Kernel in Unix/Linux?

A

Kernel is the central core component of the OS - the first program loaded on startup. Responsibilities: memory management + process scheduling + hardware communication (device drivers) + file system management + system calls interface. Key: kernel does NOT directly interact with users - it spawns a shell for user interaction. Has protected memory area that no process can overwrite. Linux kernel: monolithic with loadable modules

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is a Shell in Unix?

A

Shell is a user interface (command line interpreter) that provides access to Unix/Linux services. Takes user commands -> sends to OS for execution -> returns output. Two types: interactive (user types commands) + non-interactive (runs scripts). Also provides: environment setup + variables + scripting language + pipes + I/O redirection. Kernel spawns a shell for each user session

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are the different shells in Unix?

A

Bourne shell (sh - original Unix shell) + Bourne Again Shell (bash - most common Linux shell - enhanced sh) + Korn shell (ksh - commercial Unix) + Z shell (zsh - default on macOS since Catalina - powerful) + C shell (csh - C-like syntax) + Enhanced C shell (tcsh - improved csh) + Fish shell (user-friendly - modern). Check current shell: echo $SHELL. Change shell: chsh -s /bin/zsh

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are the main responsibilities of a Unix Shell?

A

Program execution (run commands and scripts) + Environment setup (define env variables with export) + Interpreter (built-in scripting language - if/for/while/case) + Pipeline (connect commands with pipe | - output of one becomes input of next) + I/O redirection (> stdout redirect - < stdin redirect -»_space; append - 2> stderr) + Job control (background/foreground processes) + History and tab completion

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the difference between Multi-tasking and Multi-user environments?

A

Multi-tasking: one user can run multiple tasks simultaneously - OS executes them at the same time (time-slicing). Multi-user: multiple users can interact with the OS simultaneously - each gets their own session and process space. Unix/Linux is BOTH multitasking AND multiuser. Windows Server is multiuser. Embedded systems may be single-user single-tasking

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is the difference between the Unix Kernel and Shell?

A

Kernel: core of OS - manages hardware resources - protected memory - runs in kernel space - system calls interface - processes everything at OS level. Shell: user-facing interface - interprets user commands - runs in user space - sends requests to kernel via system calls. User -> Shell -> Kernel -> Hardware. Shell is just one of many programs that use the kernel

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

MEMORY BOOSTER: Unix/Linux fundamentals

A

Kernel = core OS (memory + processes + hardware + protected). Shell = user interface (CLI + scripting + pipes + I/O redirection). Shells: sh (original) + bash (most common Linux) + zsh (macOS default) + ksh + csh. User -> Shell -> Kernel -> Hardware. Unix is both multitasking (multiple tasks per user) AND multiuser (multiple users simultaneously). Everything in Unix is a file

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the Unix file system hierarchy?

A

Root (/) is the top of the hierarchy. Key directories: /bin (essential binaries - ls - cp - rm) + /etc (config files) + /home (user home dirs) + /var (variable data - logs) + /tmp (temporary files) + /usr (user programs + libraries) + /lib (shared libraries) + /proc (virtual - process info) + /dev (device files) + /opt (optional software) + /root (root user home) + /boot (boot files + kernel)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is an Inode in Unix?

A

An Inode (Index Node) is a data structure in the Unix file system that stores file metadata. Contains: file type + permissions + owner + group + size + timestamps (created/modified/accessed) + number of hard links + pointers to data blocks on disk. Does NOT contain: filename (stored in directory entry) + file content. Each inode has a unique number. ls -i shows inode number. df -i shows inode usage

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the difference between absolute path and relative path?

A

Absolute path: complete path from root directory (/). Always starts with /. Works from any location. Example: /var/log/nginx/access.log. Relative path: path relative to current working directory. Does NOT start with /. . = current dir. .. = parent dir. ~ = home dir. Example: ./logs/app.log or ../config/settings. pwd shows current absolute path. cd changes directory using either type

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the difference between a hard link and a soft link (symlink)?

A

Hard link: another directory entry pointing to the SAME inode (same data on disk). Same file - different names. Cannot span file systems. Cannot link directories. Deleting original keeps data (multiple references to inode). Soft link (symlink): a special file containing a PATH to the target. Can span file systems. Can link directories. If target deleted -> broken symlink. ln = hard link. ln -s = soft link. ls -l shows -> for symlinks

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the first character in ls -l output?

A

ls -l first character shows file type: - (regular file) + d (directory) + l (symbolic link) + b (block special file - disk) + c (character special file - terminal) + s (socket) + p (named pipe / FIFO). Following 9 characters = permissions (rwxrwxrwx = owner/group/other). Example: -rwxr-xr– = regular file - owner rwx - group r-x - others r–

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What are Unix file permissions?

A

Three levels: owner (u) + group (g) + others (o). Three permission types: r (read=4) + w (write=2) + x (execute=1). chmod changes permissions: chmod 755 file (rwxr-xr-x) + chmod u+x file (add execute for owner) + chmod go-w file (remove write for group+others). chown changes owner: chown user:group file. Special bits: setuid (s on user x) + setgid (s on group x) + sticky bit (t on other x)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the difference between / and ~ in Unix?

A

/ is the root directory - the top of the entire file system hierarchy. All paths start from /. ~ is a shortcut for the current user’s home directory (/home/username on Linux or /Users/username on macOS). cd / goes to root. cd ~ or just cd goes to home directory. ~username = home directory of a specific user. The root user’s home is /root (not /home/root)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is a process in Unix?

A

A process is a running instance of a program. Every process has: PID (process ID) + PPID (parent PID) + owner + working directory + environment variables + open file descriptors. Process types: foreground (takes terminal control) + background (runs with & suffix) + daemon (background service - no terminal). Key commands: ps (list processes) + top/htop (real-time) + kill PID (send signal) + jobs (list background jobs)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

MEMORY BOOSTER: Unix file system

A

Inode = file metadata (permissions + owner + size + disk pointers) - NOT filename. Absolute path = starts with / (from root). Relative path = from current dir (. = here - .. = parent - ~ = home). ls -l first char: - (file) + d (dir) + l (symlink) + b/c (devices). Permissions: rwxrwxrwx (owner/group/other). chmod 755 = rwxr-xr-x. Hard link = same inode. Symlink = path pointer (can be broken). Key dirs: /etc (config) + /var (logs) + /home (users) + /tmp (temp)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What are the most important Unix file commands?

A

ls (list files - ls -la for all with details) + cd (change directory) + pwd (print working dir) + mkdir (make dir - mkdir -p creates parents) + rmdir (remove empty dir) + cp (copy - cp -r for recursive) + mv (move/rename) + rm (remove - rm -r recursive - rm -f force - rm -rf delete everything) + touch (create empty file or update timestamp) + cat (display file) + less/more (paginate) + find (search files)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How do you remove all files in current directory including subdirectories?

A

rm -r * removes all files and subdirectories recursively in current directory. The * wildcard matches all files/dirs. -r flag = recursive (descends into subdirectories). rm -rf * = recursive + force (no confirmation prompts). WARNING: rm -rf is DESTRUCTIVE and IRREVERSIBLE. Better: rm -rf /path/to/dir/* to be explicit. For safety use find first: find . -type f to preview what will be deleted

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What are the most important Unix text processing commands?

A

cat (concatenate + display files) + grep (search text - grep -r recursive - grep -i case insensitive - grep -v invert) + head (first N lines - head -5 file) + tail (last N lines - tail -f live follow) + cut (extract columns - cut -d: -f1 /etc/passwd) + sort (sort lines - sort -n numeric - sort -r reverse) + uniq (remove duplicates - needs sorted input) + wc (word count - wc -l lines) + tr (translate/delete chars)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What are the most important Unix network commands?

A

ping (test connectivity) + ssh (secure remote login - ssh user@host) + scp (secure copy - scp file user@host:/path) + curl (HTTP requests - curl -X POST - curl -H header) + wget (download files) + netstat (network connections) + ss (modern netstat) + nmap (port scanner) + ifconfig/ip (network interface config) + dig/nslookup (DNS lookup) + traceroute (trace network path) + telnet (test port connectivity)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What are the most important Unix system commands?

A

ps (process status - ps aux for all) + top/htop (real-time process monitor) + kill PID (send signal - kill -9 = SIGKILL force) + df (disk filesystem usage - df -h human readable) + du (disk usage - du -sh dir/) + free (memory usage - free -h) + uname -a (kernel + OS info) + whoami (current user) + id (user + group IDs) + uptime (system uptime) + history (command history) + man command (manual pages)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is the grep command and how do you use it?

A

grep searches for patterns in files or input. grep ‘pattern’ file + grep -r ‘pattern’ dir/ (recursive) + grep -i ‘pattern’ (case insensitive) + grep -v ‘pattern’ (invert - lines NOT matching) + grep -n ‘pattern’ (show line numbers) + grep -c (count matches) + grep -l (show filenames only) + grep -E ‘pattern’ (extended regex - same as egrep) + grep -o (only matching part). Combine with pipes: ps aux | grep java

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
What is the find command in Unix?
find searches for files in directory hierarchy. find /path -name '*.log' (by name) + find . -type f (files only) + find . -type d (dirs only) + find . -mtime -7 (modified in last 7 days) + find . -size +100M (larger than 100MB) + find . -user john (owned by user) + find . -perm 755 (specific permissions) + find . -name '*.tmp' -delete (find and delete) + find . -exec command {} \ + (execute command on each)
26
What is the difference between less and more commands?
more: oldest pager - shows file one screen at a time - can only scroll forward (spacebar) - press q to quit - limited features. less: newer - more powerful - scroll forward AND backward (arrow keys + PgUp/PgDn) - search with / + n for next match - G to end - g to beginning. less is more (pun intended). Always prefer less for viewing large files. tail -f for live log monitoring
27
What is the sed command?
sed (Stream Editor) processes text line by line applying editing commands. Most common: sed 's/old/new/g' file (substitute all occurrences) + sed 's/old/new/' file (substitute first occurrence per line) + sed -i 's/old/new/g' file (in-place edit) + sed -n '5,10p' file (print lines 5-10) + sed '/pattern/d' file (delete matching lines) + sed '5d' file (delete line 5). Powerful for batch text transformations in scripts
28
What is the awk command?
awk is a powerful text processing language. Processes text line by line splitting into fields. $1 $2 etc = field values. $0 = entire line. awk '{print $1}' file (print first field) + awk -F: '{print $1}' /etc/passwd (use : delimiter - print usernames) + awk '{sum += $1} END {print sum}' file (sum numbers) + awk 'NR==5' file (print line 5) + awk '/pattern/ {print $2}' file (print field for matching lines)
29
MEMORY BOOSTER: Essential Unix commands
Files: ls -la + cd + pwd + mkdir -p + cp -r + mv + rm -rf + touch + cat + less. Search: grep -r -i -v -n + find -name -type -mtime -size -exec. Text: sed 's/old/new/g' + awk -F: '{print $1}' + cut -d: -f1 + sort + uniq + wc -l + head -n + tail -f. System: ps aux + top + kill -9 + df -h + du -sh + free -h + uname -a. Network: ping + ssh + curl + wget + netstat/ss. rm -rf * = DESTRUCTIVE = no undo
30
What is a Pipe in Unix?
A pipe (|) connects the standard output (stdout) of one command to the standard input (stdin) of the next. Creates a pipeline of commands. Example: ps aux | grep java | wc -l (count Java processes). Data flows left to right. Each command in pipeline runs in own process concurrently. Can chain unlimited commands. Named pipes (FIFOs) persist in filesystem (mkfifo). Pipes = fundamental Unix philosophy
31
What is I/O Redirection in Unix?
Redirect input/output from/to files instead of terminal. > redirect stdout to file (overwrite). >> redirect stdout to file (append). < redirect stdin from file. 2> redirect stderr to file. 2>&1 redirect stderr to same place as stdout. &> redirect both stdout + stderr. /dev/null discards output. Examples: command > output.txt 2>&1 (capture all output) + sort < unsorted.txt > sorted.txt
32
What is a Filter in Unix?
A filter is a program that reads from stdin - transforms data - writes to stdout. Designed to work in pipelines. Common filters: cat + grep + head + tail + sort + uniq + cut + awk + sed + tr + wc. Complex pipelines combine filters: cat /etc/passwd | cut -d: -f1 | sort | uniq. Filters are reusable components. Unix philosophy: small programs that do one thing well combined via pipes to solve complex problems
33
What is Command Substitution in Unix?
Command substitution captures the output of a command and uses it as an argument. Modern syntax: $(command). Legacy syntax: `command` (backticks). Examples: files=$(ls *.log) + echo "Today is $(date)" + for user in $(cat users.txt) + do + rm $(cat files_to_delete). $(command) preferred over backticks (easier to nest + more readable). Used in scripts to capture command output into variables
34
What are the special characters in Unix?
* (wildcard - matches any characters) + ? (wildcard - matches single character) + [ ] (character class - [abc] or [a-z]) + | (pipe) + > < >> (redirection) + & (background process) + + (command separator) + $ (variable prefix) + # (comment) + \ (escape character) + ' ' (strong quoting - literal) + " " (weak quoting - allows $ expansion) + ~ (home dir) + . (current dir or hidden file prefix) + .. (parent dir)
35
What is the difference between single quotes and double quotes in Unix shell?
Single quotes ('strong quoting'): everything inside is literal - no variable expansion - no command substitution - no special chars interpreted. echo '$HOME' prints literally $HOME. Double quotes ('weak quoting'): allows variable expansion ($VAR) + command substitution ($(cmd)) but prevents word splitting and globbing. echo "$HOME" prints /home/user. No quotes: all expansions + word splitting + globbing occur
36
MEMORY BOOSTER: Pipes and redirection
Pipe |: stdout of left -> stdin of right. > overwrite stdout. >> append stdout. 2> redirect stderr. 2>&1 merge stderr to stdout. < stdin from file. /dev/null = discard. Filter = reads stdin -> transforms -> writes stdout (grep + sed + awk + cut + sort + uniq). Command substitution: $(command) captures output. Quotes: single = literal (no expansion). Double = allows $VAR and $(cmd). * = any chars wildcard. ? = single char wildcard
37
What is a Shell script?
A shell script is a text file containing shell commands executed in sequence. First line (shebang): #!/bin/bash specifies interpreter. Must be executable: chmod +x script.sh. Run: ./script.sh or bash script.sh. Scripts automate: system administration + deployment + data processing + build pipelines + scheduled tasks (cron). Bash is most common scripting shell. Python preferred for complex logic
38
What is a Shell variable and how do you use it?
Shell variables store values for use in scripts. Assign: VAR=value (no spaces around =). Use: $VAR or ${VAR}. Export to child processes: export VAR=value. Special variables: $0 (script name) + $1 $2... (positional args) + $@ (all args) + $# (number of args) + $? (last exit code) + $$ (current PID) + $! (last background PID). Unset: unset VAR. Declare read-only: readonly VAR=value
39
What is the difference between -v and -x options in Bash?
-v (verbose): prints each line of the script BEFORE substitution - shows the script as written. -x (xtrace): prints each command AFTER substitution - shows expanded commands with actual values of variables. Both are for debugging. Use: #!/bin/bash -x or bash -x script.sh or set -x inside script. Combine: -xv shows both. Most useful for debugging: -x shows exactly what commands ran with what arguments
40
What are environment variables in Unix?
Environment variables are global variables available to all processes and child processes. Set + export: export VAR=value. Common vars: PATH (directories to search for commands) + HOME (user home dir) + USER (current username) + SHELL (current shell) + PWD (current directory) + LANG (locale) + PS1 (shell prompt). View all: env or printenv. Add to PATH: export PATH=$PATH:/new/dir. Set in .bashrc or .bash_profile for persistence
41
What are the control structures in Bash scripting?
if/elif/else: if [ condition ] + then ... elif [ condition ] + then ... else ... fi. for loop: for i in {1..10} + do ... done or for file in *.txt + do. while loop: while [ condition ] + do ... done. case: case $var in pattern) ... + + esac. until: until [ condition ] + do. Test conditions: -f (file exists) + -d (dir exists) + -z (empty string) + -n (non-empty) + -eq -ne -lt -gt (numeric comparisons) + = != (string comparisons)
42
What are Bash functions?
Functions in Bash group reusable commands. Define: function_name() { commands + } or function function_name { commands + }. Call: function_name arg1 arg2. Access args inside function: $1 $2 etc (local to function). Return value: return exit_code (0=success). Capture output: result=$(my_function). Local variables: local var=value. Functions must be defined before calling. Can source function libraries: source functions.sh
43
What is the exit status in Unix?
Every Unix command returns an exit status (return code). 0 = success. Non-zero = failure (1 = general error - 2 = misuse - 126 = not executable - 127 = command not found - 130 = Ctrl+C). Check last status: $?. Use in scripts: if command + then (runs if exit 0) + command || echo 'failed' + set -e (exit script on any error). Best practice: always check exit status in scripts
44
What is set -e - set -u and set -o pipefail in Bash?
set -e: exit script immediately if any command returns non-zero exit code (fail fast). set -u: treat unset variables as error (catches typos in variable names). set -o pipefail: pipe returns exit code of first failed command (without this - pipe exit = last command). Best practice: put all three at top of scripts: set -euo pipefail. Prevents silent failures that can cause data loss or security issues
45
What is cron and how do you schedule jobs?
Cron is Unix job scheduler for running commands/scripts at scheduled times. Edit crontab: crontab -e. Format: minute hour day month weekday command. Example: 0 2 * * * /backup.sh (run at 2am daily). * = every unit. Shortcuts: @daily + @hourly + @reboot. crontab -l lists scheduled jobs. /etc/cron.d/ for system-level crons. Output goes to email by default - redirect: 0 2 * * * /backup.sh >> /var/log/backup.log 2>&1
46
What is the difference between .bashrc and .bash_profile?
.bash_profile: executed for login shells (SSH login + console login). Load once per session. Set environment variables here (export PATH...). .bashrc: executed for interactive non-login shells (opening a terminal in GUI + bash subshells). Load each time new terminal opened. Put aliases + functions + PS1 prompt here. Common practice: source .bashrc from .bash_profile to ensure consistency. zsh uses .zshrc
47
MEMORY BOOSTER: Shell scripting
Shebang: #!/bin/bash. Variables: VAR=value (no spaces) - $VAR - export VAR. Special: $0 (script) + $1..$9 (args) + $? (exit code) + $$ (PID). Debugging: -x (shows expanded) + -v (shows as-written). Best: set -euo pipefail at top. Exit 0=success nonzero=fail. Control: if [] + then + for in + do + while [] + do + case. Cron: min hour day month weekday command. .bashrc = interactive shells. .bash_profile = login shells. Function: name() { local var + }
48
How do you manage processes in Unix?
View processes: ps aux (all processes) + top (interactive - press k to kill - q to quit) + htop (better top). Kill processes: kill PID (SIGTERM - graceful) + kill -9 PID (SIGKILL - force) + killall processname + pkill pattern. Background/foreground: command & (background) + Ctrl+Z (suspend) + bg (resume in background) + fg (bring to foreground) + jobs (list background jobs). nohup command & = run after logout
49
What are Unix signals?
Signals are software interrupts sent to processes. Common signals: SIGTERM (15 - graceful termination - default kill) + SIGKILL (9 - immediate kill - cannot be caught or ignored) + SIGHUP (1 - hangup - reload config for daemons) + SIGINT (2 - Ctrl+C interrupt) + SIGSTOP (19 - pause process) + SIGCONT (18 - continue paused). Send: kill -SIGNAL PID or kill -15 PID. trap SIGNAL in scripts to handle signals
50
What is the difference between kill and kill -9?
kill PID (equivalent to kill -15 or kill -SIGTERM): sends SIGTERM - process receives signal and can clean up (close files - save state - graceful shutdown) before exiting. kill -9 PID (SIGKILL): OS immediately terminates the process - cannot be caught - ignored or blocked - no cleanup chance. Always try kill (SIGTERM) first - give process time - then kill -9 if unresponsive. kill -9 may leave resources in inconsistent state
51
What is a daemon in Unix?
A daemon is a background process that runs continuously without a controlling terminal. Names typically end in 'd': sshd + httpd + nginx + mysqld + crond + systemd. Start/stop: systemctl start/stop/status service (systemd) + service name start/stop (older). Enable at boot: systemctl enable service. Logs: journalctl -u service (systemd). Daemons respond to SIGHUP to reload config without restart. Parent of orphaned daemons = init/systemd (PID 1)
52
What is the difference between ps and top?
ps: static snapshot of current processes. ps aux shows all processes (a=all users - u=user format - x=processes without terminal). Output: PID + USER + CPU% + MEM% + command. top: real-time continuously updated process viewer. Press: k (kill) + r (renice) + q (quit) + P (sort by CPU) + M (sort by memory). htop = improved top with color + mouse support + easier navigation. Use ps for scripting - top/htop for interactive monitoring
53
MEMORY BOOSTER: Process management
ps aux = all processes snapshot. top/htop = real-time monitor. kill PID = SIGTERM (graceful). kill -9 PID = SIGKILL (force - no cleanup). Ctrl+C = SIGINT (interrupt). Ctrl+Z = SIGSTOP (suspend). bg = resume background. fg = bring foreground. jobs = list background. nohup = run after logout. Daemon = background service (sshd - nginx - crond). systemctl start/stop/enable/status. SIGHUP = reload config (kill -1). Signals: 1=HUP - 2=INT - 9=KILL - 15=TERM
54
How do you manage users in Unix/Linux?
Add user: useradd username or adduser username (interactive). Set password: passwd username. Modify user: usermod -aG groupname username (add to group). Delete user: userdel -r username (remove home dir). View users: cat /etc/passwd (format: user:x:UID:GID:comment:home:shell). Switch user: su - username (login shell) + sudo command (run as root). User info: id username + who (logged in users) + w (who + what they're doing)
55
How do you manage groups in Unix/Linux?
Create group: groupadd groupname. Add user to group: usermod -aG groupname username (must logout/login for effect) or gpasswd -a user group. Remove from group: gpasswd -d user group. View groups: cat /etc/group + groups username + id username. Primary group: first group in id output. Supplementary groups: additional groups. Group permissions apply to all users in group. chgrp changes file group
56
How do you use sudo in Unix?
sudo executes commands as root (or other user). sudo command (run as root). sudo -u username command (run as specific user). sudo -i (interactive root shell). sudo -l (list allowed commands). Configured in /etc/sudoers (edit with visudo for syntax checking). Add user to sudo: usermod -aG sudo username (Debian/Ubuntu) or wheel group (RHEL/CentOS). Log all sudo usage: /var/log/auth.log. Better than logging in as root directly
57
What is chmod and how do you use it?
chmod changes file permissions. Symbolic: chmod u+x file (add execute for owner) + chmod go-rw file (remove read/write for group+others) + chmod a+r file (add read for all). Numeric (octal): r=4 w=2 x=1. chmod 755 = rwxr-xr-x. chmod 644 = rw-r--r--. chmod 600 = rw-------. chmod 777 = rwxrwxrwx (insecure). chmod -R 755 dir (recursive). umask sets default permissions (022 = 755 for dirs - 644 for files)
58
What is chown and chgrp?
chown changes file owner and/or group. chown user file + chown user:group file + chown :group file (group only). chown -R user:group dir (recursive). chgrp changes group only: chgrp group file. Only root can change file owner. File owner can change group to one they belong to. Used in deployment scripts to set correct ownership for web server files (chown -R www-data:www-data /var/www)
59
MEMORY BOOSTER: Users and permissions
Users: useradd + passwd + usermod + userdel. /etc/passwd = user database. /etc/shadow = passwords (hashed). /etc/group = groups. sudo = run as root (configured in /etc/sudoers - edit with visudo). chmod: rwx=421. 755=rwxr-xr-x (typical dir). 644=rw-r--r-- (typical file). 600=rw------- (private key). chmod u+x = add execute. chown user:group file. chown -R recursive. id = show current user + groups. su - = switch user (login shell)
60
How do you use SSH in Unix/Linux?
SSH (Secure Shell) for encrypted remote access. Connect: ssh user@hostname or ssh -p 2222 user@host (custom port). Key-based auth (passwordless): ssh-keygen (generate key pair) -> ssh-copy-id user@host (copy public key to server). Keys stored: ~/.ssh/ (id_rsa private - id_rsa.pub public - authorized_keys - known_hosts). SSH tunnel: ssh -L localPort:remoteHost:remotePort user@sshServer. Config file: ~/.ssh/config
61
How do you copy files between hosts in Unix?
scp (secure copy over SSH): scp file user@host:/path + scp user@host:/path/file . + scp -r dir user@host:/path (recursive). rsync (efficient sync): rsync -avz source/ user@host:/dest (archive + verbose + compress) + rsync --delete (delete files not in source). rsync only transfers changed parts (efficient for large syncs). sftp (interactive FTP over SSH): sftp user@host -> put/get commands
62
How do you check network connectivity and port status?
ping host (ICMP reachability + latency). traceroute host (path + hops). nc (netcat) -zv host port (test if port open). nmap -p 80 host (port scan). curl -I http://host (HTTP headers). telnet host port (old but useful for port testing). ss -tlnp (listening TCP ports). netstat -tlnp (listening ports - older). ss -s (socket statistics). lsof -i :8080 (process using port 8080)
63
MEMORY BOOSTER: Unix networking
SSH: ssh user@host + key auth: ssh-keygen -> ssh-copy-id. ~/.ssh/config for shortcuts. SCP: scp file user@host:/path. rsync: rsync -avz src/ user@host:/dest (efficient - only transfers changes). Check connectivity: ping + traceroute + nc -zv host port + curl -I http://host. Check ports: ss -tlnp + lsof -i :8080. DNS: dig hostname + nslookup hostname. IP config: ip addr show or ifconfig. Routes: ip route show or netstat -r
64
How do you search for text in files in Unix?
grep 'pattern' file: search single file. grep -r 'pattern' dir/: recursive search. grep -rn 'pattern' dir/: with line numbers. grep -rl 'pattern' dir/: filenames only. grep -i 'pattern': case insensitive. egrep or grep -E 'pattern1|pattern2': extended regex. grep -v 'pattern': invert (exclude). ag (silver searcher) and ripgrep (rg): faster alternatives. find + grep combo: find . -name '*.java' -exec grep -l 'pattern' {} \ +
65
How do you sort and process text in Unix?
sort file (alphabetical) + sort -n (numeric) + sort -r (reverse) + sort -k2 (by field 2) + sort -t: -k3 (delimiter : field 3) + sort -u (unique - remove dups). uniq (remove adjacent duplicates - needs sorted input): uniq -c (count occurrences) + uniq -d (only duplicates). Pipeline: cat file | sort | uniq -c | sort -rn (count occurrences sorted by frequency). cut -d: -f1,3 /etc/passwd (extract fields 1 and 3)
66
How do you view and edit files in Unix?
View: cat (small files) + less (large files - searchable) + head -20 file (first 20 lines) + tail -20 file (last 20) + tail -f file (live follow). Edit: vi/vim (modal editor - i=insert - Esc=normal - :w save - :q quit - :wq save+quit - :q! force quit - dd delete line - yy copy line - p paste - /search). nano (simpler - Ctrl+X exit). sed -i for non-interactive editing. diff file1 file2 shows differences. patch applies diff
67
What is xargs in Unix?
xargs reads stdin and builds + executes commands. Converts stdin to command arguments. Example: find . -name '*.tmp' | xargs rm (delete all .tmp files). echo 'file1 file2' | xargs touch. ls *.log | xargs grep 'ERROR'. -n 1 processes one item at a time. -P 4 runs 4 processes in parallel. -I {} placeholder: find . -name '*.java' | xargs -I {} cp {} /backup/. Solves 'argument list too long' errors from wildcards
68
What is tee command in Unix?
tee reads from stdin and writes to BOTH stdout AND a file simultaneously. command | tee file.txt (writes to file AND shows on screen). command | tee -a file.txt (append mode). Useful for: seeing output while also saving to log + splitting pipeline output. Example: make build 2>&1 | tee build.log (captures build output while showing it). Without tee you have to choose: see it OR save it. With tee: do both
69
What is the diff and patch command?
diff: compares two files showing differences. diff file1 file2 (default output) + diff -u file1 file2 (unified format - most readable - used for patches) + diff -r dir1 dir2 (compare directories). patch: applies a diff to original file to create modified version. patch original.txt changes.patch. Used in: software development (patch files) + git diff shows unified diff. vimdiff = visual side-by-side diff in vim
70
MEMORY BOOSTER: Text processing
grep -rn (recursive + line numbers). awk -F: '{print $1}' (field separator + print field). sed 's/old/new/g' (global substitute) + sed -i (in-place edit). sort | uniq -c | sort -rn (frequency count). cut -d: -f1 (extract field). head/tail -n + tail -f (live follow). xargs: pipe to command args (find . -name '*.tmp' | xargs rm). tee: write to file AND stdout simultaneously. vi: i=insert Esc=normal :wq=save+quit dd=delete line /=search
71
What are the package managers in Linux?
APT (Debian/Ubuntu): apt update (refresh package list) + apt install package + apt remove + apt upgrade + apt search. YUM/DNF (RHEL/CentOS/Fedora): yum install + dnf install + yum update + yum remove + yum search. Zypper (openSUSE). Pacman (Arch). For Python: pip. Node: npm. Most scripts use apt-get for Debian or yum for RHEL for maximum compatibility. Package managers resolve dependencies automatically
72
How do you check disk usage in Unix?
df -h: shows disk filesystem usage (human-readable GB/MB). df -i: shows inode usage. du -sh /path: disk usage of directory (summary + human). du -sh *: usage of each item in current directory. du -sh /* | sort -rh: find largest directories. Useful for: finding which directories consume most space + checking if disk is full. /dev/full vs /dev/null. lsblk: list block devices. fdisk -l: partition info
73
What is log management in Unix?
System logs in /var/log/: syslog/messages (general system) + auth.log (authentication) + kern.log (kernel) + nginx/access.log + mysql/error.log. View logs: tail -f /var/log/syslog (live). journalctl (systemd logs): journalctl -u nginx (specific service) + journalctl -f (follow) + journalctl --since '1 hour ago'. logrotate: rotates + compresses + deletes old logs automatically (/etc/logrotate.d/). grep errors: grep -i error /var/log/syslog
74
MEMORY BOOSTER: System administration
Package mgmt: apt install (Ubuntu/Debian) + yum/dnf install (RHEL/CentOS). Disk: df -h (filesystem usage) + du -sh dir/ (directory size) + du -sh * | sort -rh (find large dirs). Logs: /var/log/ + tail -f syslog + journalctl -u service -f. Process: systemctl start/stop/status/enable. Cron: crontab -e (min hour day month weekday cmd). SSH key setup: ssh-keygen -> ssh-copy-id. Environment: export PATH=$PATH:/new/path in .bashrc