---
title: "Red Hat System Administration I Flashcards (RH124)"
description: "Full course coverage for Red Hat System Administration I (RH124-9.0) using spaced repetition. Covers CLI, files, users, processes, networking, storage, DNF, systemd, logging, and shell scripting."
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/flashcards/post/redhat-system-administration-rh124-flashcards
---

# Red Hat System Administration I Flashcards (RH124)

## Flashcards

### 1. What is the RHEL shell prompt and what does $ vs

The shell prompt is where you type commands. A $ prompt means you are logged in as a regular user. A

### 2. What command shows the current logged-in user?

The whoami command prints the username of the currently logged-in user.

```
$ whoami
mohammad

```

### 3. What does the pwd command do?

pwd (print working directory) displays the absolute path of the current directory you are in.

```
$ pwd
/home/mohammad

```

### 4. What is the difference between an absolute path and a relative path?

An absolute path starts from the root directory (/) and fully describes a file's location regardless of the current directory. A relative path is relative to the current working directory and does not start with /.

```
# Absolute
/home/mohammad/docs/file.txt
# Relative (from /home/mohammad)
docs/file.txt

```

### 5. What does the man command do?

man (manual) displays the built-in reference manual page for a command. It describes the command's purpose, syntax, options, and examples.

```
$ man ls
$ man 5 passwd   # section 5 = file formats

```

### 6. How do you get a short description of a command's purpose?

Use whatis to show a one-line description from the man page database, or use the --help flag to get a brief usage summary directly from the command.

```
$ whatis ls
ls (1) - list directory contents
$ ls --help

```

### 7. What is tab completion in bash?

Tab completion automatically completes a command, filename, or path when you press the Tab key. Press Tab once to complete if unique; press Tab twice to list all matching options when there are multiple choices.

### 8. How do you view and search command history in bash?

The history command lists previously run commands with line numbers. Use Ctrl+R to search history interactively. Re-run a command with !N (by number) or !! to repeat the last command.

```
$ history
$ !42       # run command number 42
$ !!        # repeat last command

```

### 9. What does the echo command do?

echo prints text or the value of variables to standard output. It is commonly used in scripts and to inspect environment variable values.

```
$ echo "Hello, World!"
$ echo $HOME
/home/mohammad

```

### 10. What is the difference between su and sudo?

su (switch user) opens a new shell as another user (commonly root), requiring that user's password. sudo runs a single command with elevated privileges using your own password, based on rules in /etc/sudoers. sudo is preferred for auditability and security.

```
$ su -          # switch to root (full login shell)
$ sudo dnf update   # run one command as root

```

### 11. How do you switch to root using sudo without knowing the root password?

If your account is in the wheel group or has sudo privileges, run sudo -i or sudo su - to open an interactive root shell using your own password.

```
$ sudo -i
# whoami
root

```

### 12. What does the clear command and Ctrl+L do?

Both clear the terminal screen. Ctrl+L is the keyboard shortcut equivalent of the clear command and works faster in practice.

### 13. What is a virtual console in RHEL?

RHEL provides multiple virtual consoles (tty1–tty6) accessible via Ctrl+Alt+F1 through F6. Each is an independent login session. The graphical desktop typically runs on tty1. Switch between them using Ctrl+Alt+Fn.

### 14. What does the ls command do and what are common options?

ls lists directory contents. Common options -l (long format with permissions, owner, size, date), -a (show hidden files starting with .), -h (human-readable sizes), -R (recursive), -t (sort by modification time).

```
$ ls -lah /etc

```

### 15. How do you create a directory in Linux?

Use mkdir to create a directory. Use the -p flag to create parent directories as needed without errors.

```
$ mkdir mydir
$ mkdir -p /tmp/a/b/c   # creates all parents

```

### 16. How do you copy files and directories?

Use cp to copy files. Add -r (recursive) to copy directories and their contents. Use -p to preserve permissions and timestamps.

```
$ cp file.txt /tmp/
$ cp -r mydir/ /tmp/mydir_backup/

```

### 17. How do you move or rename files?

Use mv to move a file to a different location or rename it in place. If the destination is a different name in the same directory, it renames the file.

```
$ mv old.txt new.txt        # rename
$ mv file.txt /tmp/         # move

```

### 18. How do you remove files and directories?

Use rm to delete files. Use rm -r to recursively delete a directory and its contents. Use rmdir to remove empty directories only.

```
$ rm file.txt
$ rm -r mydir/
$ rmdir emptydir/

```

### 19. What does the touch command do?

touch creates an empty file if it does not exist, or updates the access and modification timestamps of an existing file to the current time.

```
$ touch newfile.txt

```

### 20. What is the difference between a hard link and a soft (symbolic) link?

A hard link is a second directory entry pointing to the same inode (data blocks) deleting the original does not affect the hard link. A soft link (symlink) is a pointer to a path if the original is deleted, the symlink breaks.

```
$ ln file.txt hardlink.txt          # hard link
$ ln -s file.txt softlink.txt       # symbolic link

```

### 21. How do you find files in Linux?

Use find to search for files by name, type, size, owner, or modification time. Use locate for a faster indexed search (requires updatedb to be run first).

```
$ find /etc -name "*.conf"
$ find /home -type f -size +10M
$ locate passwd

```

### 22. How do you view file contents in the terminal?

Use cat to print the full file. Use less for paginated scrolling (q to quit). Use head to show the first N lines and tail to show the last N lines. tail -f follows a file in real time.

```
$ cat /etc/hostname
$ less /var/log/messages
$ head -20 /etc/passwd
$ tail -f /var/log/secure

```

### 23. What is I/O redirection in bash?

I/O redirection changes where a command reads input from or sends output to. > redirects stdout to a file (overwrite), >> appends, < reads input from a file, 2> redirects stderr, and 2>&1 combines stderr with stdout.

```
$ ls /etc > output.txt        # overwrite
$ echo "line" >> file.txt     # append
$ command 2>/dev/null         # discard errors

```

### 24. What is a pipe (|) in Linux?

A pipe connects the stdout of one command to the stdin of the next, allowing you to chain commands. It is one of the most powerful features of the Linux shell.

```
$ ps aux | grep httpd
$ cat /etc/passwd | wc -l
$ df -h | sort -k5 -rn

```

### 25. What does grep do?

grep searches for lines matching a pattern in a file or stdin. Common options -i (case-insensitive), -r (recursive), -n (show line numbers), -v (invert match, show non-matching lines), -E (extended regex).

```
$ grep "root" /etc/passwd
$ grep -rn "error" /var/log/
$ grep -v "^#" /etc/ssh/sshd_config

```

### 26. What does the wc command do?

wc (word count) counts lines, words, and characters in a file or stdin. -l counts only lines, -w only words, -c only bytes.

```
$ wc -l /etc/passwd
45 /etc/passwd

```

### 27. What is the /etc/passwd file?

/etc/passwd stores user account information one line per user with seven colon-separated fields username, password placeholder (x), UID, GID, GECOS (comment), home directory, and login shell.

```
# username:x:UID:GID:comment:home:shell
mohammad:x:1000:1000:Mohammad:/home/mohammad:/bin/bash

```

### 28. What is the /etc/shadow file?

/etc/shadow stores hashed passwords and password aging information for user accounts. It is readable only by root, providing security by separating credentials from world-readable /etc/passwd.

### 29. How do you create, modify, and delete a user?

Use useradd to create, usermod to modify, and userdel to delete users. Add -r to userdel to also remove the home directory.

```
$ sudo useradd -m -s /bin/bash ali
$ sudo usermod -aG wheel ali    # add to wheel group
$ sudo userdel -r ali           # delete + home dir

```

### 30. How do you set or change a user password?

Use passwd to set or change a user's password. Root can change any user's password without knowing the current one; regular users must provide their current password.

```
$ sudo passwd ali       # set ali's password
$ passwd                # change your own password

```

### 31. What is the /etc/group file?

/etc/group stores group account information group name, password placeholder, GID, and a comma-separated list of member usernames. It defines group membership for access control.

### 32. How do you create and manage groups?

Use groupadd to create a group, groupmod to modify it, and groupdel to delete it. Use usermod -aG to add a user to a supplementary group (the -a flag appends rather than replacing).

```
$ sudo groupadd devteam
$ sudo usermod -aG devteam mohammad
$ sudo groupdel devteam

```

### 33. What are Linux file permissions and how do you read them?

Permissions are shown as a 10-character string. The first character is the file type (- file, d directory, l symlink). The next 9 are three sets of rwx owner, group, others. r=read(4), w=write(2), x=execute(1).

```
-rwxr-xr-- 1 root wheel 4096 Jan 1 12:00 script.sh
# owner: rwx, group: r-x, others: r--

```

### 34. How do you change file permissions with chmod?

chmod changes file permissions. Use symbolic mode (u/g/o/a + r/w/x) or octal notation (e.g., 755). -R applies recursively to directories.

```
$ chmod 755 script.sh        # rwxr-xr-x
$ chmod u+x,g-w file.txt     # symbolic
$ chmod -R 644 /var/www/html

```

### 35. How do you change file ownership with chown?

chown changes the owner and/or group of a file. Use user:group syntax to change both at once. -R applies recursively.

```
$ sudo chown ali file.txt
$ sudo chown ali:devteam file.txt
$ sudo chown -R nginx:nginx /var/www/

```

### 36. What is the umask and how does it work?

umask defines the default permissions subtracted when creating new files and directories. A umask of 022 results in files with 644 (666-022) and directories with 755 (777-022).

```
$ umask          # view current umask
0022
$ umask 027      # set new umask

```

### 37. What are special permissions SUID, SGID, and sticky bit?

SUID (4) on executables, runs with the file owner's privileges (e.g., passwd runs as root). SGID (2) on executables, runs with group's privileges; on directories, new files inherit the group. Sticky bit (1) on directories, only the file owner can delete their own files (e.g., /tmp).


```
$ chmod u+s /usr/bin/someprog   # SUID
$ chmod g+s /shared/            # SGID on dir
$ chmod +t /tmp                 # sticky bit

```

### 38. What is a process in Linux?

A process is a running instance of a program. Each process has a unique PID (Process ID), a parent process (PPID), an owner, and resource usage stats. The first process started at boot is systemd with PID 1.

### 39. How do you view running processes?

Use ps to get a snapshot of processes. ps aux shows all processes with detailed info. top and htop provide interactive real-time views of process activity and resource usage.

```
$ ps aux
$ ps -ef
$ top
$ htop

```

### 40. How do you send signals to processes?

Use kill to send signals by PID, or killall/pkill to match by name. The most common signals are SIGTERM (15) for graceful shutdown and SIGKILL (9) for immediate termination.

```
$ kill 1234           # SIGTERM (default)
$ kill -9 1234        # SIGKILL
$ killall httpd
$ pkill -u ali        # kill all processes by user

```

### 41. What is the difference between SIGTERM and SIGKILL?

SIGTERM (15) asks a process to terminate gracefully the process can catch it, clean up, and exit. SIGKILL (9) immediately terminates the process at the kernel level and cannot be caught, blocked, or ignored.

### 42. What are foreground and background jobs in bash?

A foreground job runs interactively and holds the terminal. A background job runs independently with & appended. Use Ctrl+Z to suspend a foreground job, bg to resume it in the background, fg to bring it to the foreground, and jobs to list active jobs.

```
$ sleep 300 &       # start in background
$ jobs              # list jobs
$ fg %1             # bring job 1 to foreground
$ bg %1             # resume job 1 in background

```

### 43. What does the nice and renice command do?

nice launches a process with a specified niceness value (-20 highest priority to 19 lowest). renice changes the priority of an already-running process. Only root can set negative (higher priority) values.

```
$ nice -n 10 tar czf backup.tar.gz /data
$ renice -n 5 -p 1234

```

### 44. What does the top command show?

top displays a real-time, dynamic view of running processes sorted by CPU usage by default. It shows load averages, memory/swap usage, and per-process stats. Press M to sort by memory, P by CPU, k to kill, q to quit.

### 45. What is a zombie process?

A zombie process has finished execution but its entry remains in the process table because its parent has not yet read its exit status via wait(). Zombies consume minimal resources but indicate a bug in the parent process.

### 46. What does the pgrep and pstree command do?

pgrep finds PIDs matching a name pattern without needing ps | grep. pstree displays processes in a visual tree showing parent-child relationships.

```
$ pgrep sshd
$ pstree -p

```

### 47. How do you view network interface configuration in RHEL 9?

Use ip addr (or ip a) to display all network interfaces and their IP addresses. ip link shows interface state. The older ifconfig command is deprecated in RHEL 9.

```
$ ip addr show
$ ip addr show eth0
$ ip link show

```

### 48. How do you view the routing table in RHEL 9?

Use ip route (or ip r) to display the kernel routing table, showing the default gateway and network routes.

```
$ ip route show
default via 192.168.1.1 dev eth0

```

### 49. What is NetworkManager and nmcli?

NetworkManager is the default network management service in RHEL 9. nmcli is its command-line interface for managing connections, devices, and network settings without editing config files directly.

```
$ nmcli connection show
$ nmcli device status
$ nmcli con up "Wired connection 1"

```

### 50. How do you test network connectivity in Linux?

Use ping to send ICMP echo requests to a host. Use traceroute (or tracepath) to trace the route packets take. Use ss or netstat to view open ports and connections.

```
$ ping -c 4 8.8.8.8
$ traceroute google.com
$ ss -tuln         # listening ports

```

### 51. What is the /etc/hosts file?

/etc/hosts is a local file that maps hostnames to IP addresses. It is checked before DNS resolution. Entries here override DNS for local name resolution.

```
# /etc/hosts
127.0.0.1   localhost
192.168.1.10  myserver.local myserver

```

### 52. What is the /etc/resolv.conf file?

/etc/resolv.conf configures DNS resolution by specifying nameserver addresses and the default search domain. In RHEL 9 with NetworkManager, this file is typically managed automatically.

```
nameserver 8.8.8.8
nameserver 8.8.4.4
search example.com

```

### 53. How do you connect to a remote server using SSH?

Use the ssh command to open a secure encrypted shell session to a remote host. Specify the user with user@host or the -l flag. Use -p to specify a non-default port.

```
$ ssh mohammad@192.168.1.10
$ ssh -p 2222 mohammad@server.example.com

```

### 54. How do you set up SSH key-based authentication?

Generate a key pair with ssh-keygen, then copy the public key to the remote server with ssh-copy-id. Future logins use the private key instead of a password.

```
$ ssh-keygen -t ed25519
$ ssh-copy-id mohammad@192.168.1.10

```

### 55. How do you securely copy files between hosts?

Use scp to copy files over SSH. Use rsync for efficient, incremental transfers, especially for large or frequently updated directories. rsync only transfers changed blocks.

```
$ scp file.txt mohammad@server:/tmp/
$ rsync -avz /local/dir/ mohammad@server:/remote/dir/

```

### 56. What is the purpose of the ~/.ssh/config file?

The SSH client config file defines shortcuts and settings for SSH connections aliases, usernames, ports, identity files, and jump hosts. It simplifies connecting to frequently used servers.

```
Host myserver
  HostName 192.168.1.10
  User mohammad
  Port 2222
  IdentityFile ~/.ssh/id_ed25519

```

### 57. How do you view disk usage and free space in Linux?

Use df -h to show disk space usage for all mounted filesystems in human-readable form. Use du -sh to show the size of a specific directory.

```
$ df -h
$ du -sh /var/log/
$ du -h --max-depth=1 /home/

```

### 58. What is a partition and how do you list block devices?

A partition is a logical division of a physical disk. Use lsblk to list all block devices and their mount points in a tree view. Use fdisk -l or blkid to inspect partition details and UUIDs.

```
$ lsblk
$ sudo fdisk -l /dev/sda
$ sudo blkid

```

### 59. What is a filesystem and how do you create one?

A filesystem organizes how data is stored on a partition. RHEL 9 defaults to XFS. Use mkfs to create a filesystem on a block device or partition.

```
$ sudo mkfs.xfs /dev/sdb1
$ sudo mkfs.ext4 /dev/sdb2

```

### 60. How do you mount and unmount a filesystem?

Use mount to attach a filesystem to a directory (mount point). Use umount to detach it. The device or UUID and mount point are required.

```
$ sudo mount /dev/sdb1 /mnt/data
$ sudo mount UUID="abc-123" /mnt/data
$ sudo umount /mnt/data

```

### 61. What is /etc/fstab and why is it important?

/etc/fstab defines filesystems to be automatically mounted at boot. Each line specifies the device (or UUID), mount point, filesystem type, mount options, dump flag, and fsck order. Misconfigured fstab can prevent the system from booting.

```
# device         mountpoint  fstype  options       dump pass
UUID=abc-123     /data       xfs     defaults      0    2

```

### 62. What is a logical volume in LVM?

LVM (Logical Volume Manager) abstracts physical disks into flexible logical volumes. Physical Volumes (PV) → Volume Groups (VG) → Logical Volumes (LV). LVs can be resized online, unlike raw partitions.

```
$ sudo pvcreate /dev/sdb
$ sudo vgcreate datavg /dev/sdb
$ sudo lvcreate -L 10G -n datalv datavg
$ sudo mkfs.xfs /dev/datavg/datalv

```

### 63. How do you extend a logical volume and its filesystem?

Use lvextend to grow the logical volume, then resize2fs (ext4) or xfs_growfs (XFS) to expand the filesystem to fill the new space. XFS can only grow, not shrink.

```
$ sudo lvextend -L +5G /dev/datavg/datalv
$ sudo xfs_growfs /data         # XFS
$ sudo resize2fs /dev/datavg/datalv  # ext4

```

### 64. What is a swap partition and how do you manage it?

Swap space extends RAM by using disk space as virtual memory. Use swapon/swapoff to enable or disable swap. mkswap formats a partition or file as swap. View swap usage with free -h or swapon --show.

```
$ sudo mkswap /dev/sdb2
$ sudo swapon /dev/sdb2
$ free -h
$ swapon --show

```

### 65. What is DNF and what replaced it from YUM?

DNF (Dandified YUM) is the default package manager in RHEL 8/9, replacing YUM. It resolves dependencies automatically, installs/updates/removes RPM packages from configured repositories, and is faster and more reliable than YUM.

### 66. What are the most common DNF commands?

$ dnf install <pkg>     install a package $ dnf remove <pkg>      remove a package $ dnf update            update all packages $ dnf search <keyword>  search for a package $ dnf info <pkg>        show package details $ dnf list installed    list installed packages $ dnf history           show transaction history


### 67. How do you manage DNF repositories?

Repository config files live in /etc/yum.repos.d/ with .repo extension. Use dnf repolist to list enabled repos. Use dnf config-manager --enable/--disable to toggle repos. Add repos with dnf config-manager --add-repo.

```
$ dnf repolist
$ sudo dnf config-manager --enable codeready-builder
$ ls /etc/yum.repos.d/

```

### 68. What is an RPM package?

RPM (Red Hat Package Manager) is the binary package format used by RHEL. RPM packages contain compiled binaries, configuration files, and metadata. The rpm command manages packages locally without dependency resolution.

### 69. What are common rpm commands?

$ rpm -ivh pkg.rpm      install a local RPM $ rpm -qa               list all installed packages $ rpm -qi <pkg>         query package info $ rpm -ql <pkg>         list files in package $ rpm -qf /path/to/file find which package owns a file $ rpm -e <pkg>          erase (remove) a package


### 70. What is a DNF module and application stream?

DNF modules provide multiple versions of software (e.g., Python 3.9 and 3.11) in separate streams. You choose a stream, enable it, and install the module profile. This lets you run different software versions on the same OS.

```
$ dnf module list
$ dnf module enable python39:3.9
$ dnf module install python39

```

### 71. How do you use dnf to perform a rollback?

dnf history records all transactions. Use dnf history undo <id> to reverse a specific transaction (e.g., an accidental install or update), restoring the previous state.

```
$ dnf history
$ sudo dnf history undo 15

```

### 72. What is systemd?

systemd is the init system and service manager for RHEL 9. It is PID 1, starts all other processes, manages services (units), handles logging (journald), mounts filesystems, and manages the boot process in parallel for faster startup.

### 73. What is a systemd unit?

A unit is a systemd configuration file describing a resource to manage. Types include .service (daemons), .socket (IPC), .timer (scheduled tasks), .mount (filesystems), .target (grouping units), and .path (file path monitoring).

### 74. What are the most common systemctl commands?

$ systemctl start <svc>    start a service $ systemctl stop <svc>     stop a service $ systemctl restart <svc>  restart a service $ systemctl reload <svc>   reload config without restart $ systemctl enable <svc>   enable at boot $ systemctl disable <svc>  disable at boot $ systemctl status <svc>   show status and recent logs $ systemctl is-active <svc> $ systemctl is-enabled <svc>


### 75. What is the difference between systemctl start and systemctl enable?

systemctl start launches the service immediately in the current session. systemctl enable creates symlinks so the service starts automatically at the next boot. Use both together to start now and persist across reboots.

```
$ sudo systemctl enable --now sshd
# equivalent to enable + start in one command

```

### 76. What is a systemd target?

A target is a grouping of units that represents a system state (similar to runlevels). Common targets multi-user.target (non-graphical, multi-user), graphical.target (with GUI), rescue.target (single-user), emergency.target.

```
$ systemctl get-default           # show default target
$ sudo systemctl set-default multi-user.target
$ sudo systemctl isolate rescue.target

```

### 77. How do you view all failed services?

Use systemctl --failed to list all units that have entered a failed state. Use systemctl status <unit> to investigate the specific failure and view recent journal output.

```
$ systemctl --failed
$ systemctl status httpd.service

```

### 78. How do you create a simple custom systemd service?

Create a .service unit file in /etc/systemd/system/, define [Unit], [Service], and [Install] sections, then reload the daemon and enable the service.

```
# /etc/systemd/system/myapp.service
[Unit]
Description=My Application
After=network.target

[Service]
ExecStart=/usr/local/bin/myapp
Restart=always

[Install]
WantedBy=multi-user.target

$ sudo systemctl daemon-reload
$ sudo systemctl enable --now myapp

```

### 79. What is systemd-journald?

systemd-journald is the logging component of systemd. It collects logs from the kernel, services, and applications into a structured binary journal. Logs are queried with the journalctl command.

### 80. What are common journalctl commands?

$ journalctl                   show all logs $ journalctl -u sshd           logs for a specific unit $ journalctl -f                follow (like tail -f) $ journalctl -p err            filter by priority (err, warn, info, debug) $ journalctl --since "1 hour ago" $ journalctl --since "2024-01-01" --until "2024-01-02" $ journalctl -b                logs since last boot $ journalctl -b -1             logs from previous boot


### 81. What is rsyslog?

rsyslog is the traditional syslog daemon in RHEL. It receives log messages and routes them to files in /var/log/ based on facility and severity rules in /etc/rsyslog.conf. It works alongside journald journald can forward messages to rsyslog.

### 82. What are important log files in /var/log/?

/var/log/messages general system messages /var/log/secure   authentication and sudo events /var/log/boot.log boot messages /var/log/cron     cron job execution /var/log/dnf.log  package manager activity /var/log/audit/audit.log SELinux and audit events


### 83. What is logrotate?

logrotate automatically rotates, compresses, and deletes old log files based on rules in /etc/logrotate.conf and /etc/logrotate.d/. This prevents log files from consuming all disk space.

### 84. How do you make journald logs persistent across reboots?

By default, journald stores logs in /run/log/journal (lost on reboot). To make logs persistent, create /var/log/journal/ journald will then store logs there permanently.

```
$ sudo mkdir -p /var/log/journal
$ sudo systemctl restart systemd-journald

```

### 85. What is an environment variable?

An environment variable is a named value stored in the shell environment and passed to child processes. Common ones include PATH (command search directories), HOME (user home), USER, SHELL, and LANG.

```
$ echo $PATH
$ printenv HOME
$ export MYVAR="hello"   # set and export

```

### 86. What is the difference between export and a local variable?

A variable set without export exists only in the current shell. export makes the variable available to child processes (subshells and commands launched from the shell).

```
$ MYVAR="local only"
$ export MYVAR           # now available to child processes
$ export MYVAR="hello"   # set and export in one step

```

### 87. What files are sourced for bash environment configuration?

Login shells read: /etc/profile → ~/.bash_profile → ~/.bashrc Interactive non-login shells read: ~/.bashrc → /etc/bashrc /etc/profile.d/*.sh scripts are sourced for system-wide settings. Modifications to PATH or aliases usually go in ~/.bashrc.


### 88. How do you write a basic bash script?

A bash script starts with a shebang line (#!/bin/bash), contains commands, and must be made executable with chmod +x before running.

```
#!/bin/bash
# My first script
echo "Hello, $USER!"
DATE=$(date +%Y-%m-%d)
echo "Today is $DATE"

```

### 89. How do you use variables in bash scripts?

Assign variables with NAME=value (no spaces around =). Reference them with $NAME or ${NAME}. Command substitution captures command output with $(command).

```
#!/bin/bash
NAME="Mohammad"
UPTIME=$(uptime -p)
echo "Hello $NAME, uptime: $UPTIME"

```

### 90. How do you write an if/else statement in bash?

Use if [ condition ]; then ... elif ...; else ...; fi syntax. Common test operators -f (file exists), -d (directory), -z (empty string), -eq (equal integers), -ne, -lt, -gt.

```
#!/bin/bash
if [ -f /etc/passwd ]; then
  echo "File exists"
else
  echo "File not found"
fi

```

### 91. How do you write a for loop in bash?

Use for variable in list; do ... done. Iterate over a list, a range, or command output.

```
#!/bin/bash
for USER in ali sara omar; do
  echo "Creating user: $USER"
  sudo useradd $USER
done

for i in {1..5}; do
  echo "Number: $i"
done

```

### 92. How do you write a while loop in bash?

Use while [ condition ]; do ... done. The loop runs as long as the condition is true.

```
#!/bin/bash
COUNT=1
while [ $COUNT -le 5 ]; do
  echo "Count: $COUNT"
  ((COUNT++))
done

```

### 93. What are bash positional parameters?

Positional parameters are arguments passed to a script. $0 is the script name, $1–$9 are the first nine arguments, $@ is all arguments as separate words, $# is the count of arguments.

```
#!/bin/bash
echo "Script: $0"
echo "First arg: $1"
echo "All args: $@"
echo "Count: $#"

```

### 94. What is the exit status of a command?

Every command returns an exit status (return code) between 0 and 255. 0 means success; any non-zero value indicates failure. Check it with $?. Use exit N in a script to set its exit status.

```
$ ls /etc
$ echo $?    # 0 = success
$ ls /nonexistent
$ echo $?    # 2 = error

```

### 95. What is the difference between single quotes and double quotes in bash?

Single quotes preserve the literal value of every character no variable expansion or command substitution occurs. Double quotes allow variable expansion ($VAR) and command substitution ($(cmd)) but prevent word splitting and glob expansion.

```
NAME="Mohammad"
echo '$NAME'   # prints: $NAME   (literal)
echo "$NAME"   # prints: Mohammad (expanded)

```

### 96. What is an alias in bash?

An alias creates a shortcut for a command or command with options. Define temporary aliases in the shell or add permanent ones to ~/.bashrc. Use unalias to remove.

```
$ alias ll='ls -lah'
$ alias grep='grep --color=auto'
$ unalias ll

```
