🐧

Top 92 Linux / Shell Scripting Interview Questions & Answers (2026)

92 Questions 44 Beginner 31 Intermediate 17 Advanced

About Linux / Shell Scripting

Top 100 Linux and Shell Scripting interview questions covering commands, file system, permissions, bash scripting, process management, and advanced system administration. Companies hiring for Linux / Shell Scripting roles test this knowledge at every stage — from first-round screens that check the basics to final-round conversations about real-world trade-offs.

What to Expect in a Linux / Shell Scripting Interview

Expect a mix of conceptual and practical Linux / Shell Scripting questions: clear definitions and core-concept checks for junior roles, hands-on scenario questions for mid-level roles, and architecture or trade-off discussions for senior roles. Interviewers usually move from foundational topics toward the kind of problems you'd actually face on the job.

How to Use This Guide

Work through the Linux / Shell Scripting questions in order — Beginner, then Intermediate, then Advanced — so each concept builds on the last. Every question has its own page; bookmark the ones that trip you up and revisit them the day before your interview.

Curated by Tech Baithak Editorial Team  ·  Last updated: June 2026

Beginner 44 questions

Core concepts every Linux / Shell Scripting developer must know.

01

What is Linux?

Linux is a free, open-source operating system kernel created by Linus Torvalds in 1991. It is based on the Unix philosophy and powers everything from personal computers and servers to smartphones (Android) and supercomputers. A complete Linux OS — often called a Linux distribution (distro) — bundles the kernel with a package manager, shell, utilities, and desktop environment. Popular distros include Ubuntu, CentOS, Debian, Fedora, and Arch Linux. Linux is renowned for its stability, security, and flexibility in server and cloud environments.

Open this question on its own page
02

What is the Linux kernel?

The Linux kernel is the core component of the Linux OS that manages hardware resources and provides essential services to all other software. It handles process scheduling, memory management, device drivers, file systems, and networking. The kernel runs in privileged mode (kernel space) and acts as a bridge between user applications and the physical hardware. User programs communicate with the kernel via system calls (e.g., read(), write(), fork()). The kernel is monolithic but supports loadable modules, allowing drivers to be added/removed without rebooting.

Open this question on its own page
03

What is a shell in Linux?

A shell is a command-line interpreter that accepts user commands and passes them to the operating system for execution. It serves as an interface between the user and the kernel. Common shells include Bash (Bourne Again Shell — default on most Linux distros), sh (Bourne shell), zsh, fish, and ksh. The shell also provides scripting capabilities: variables, loops, conditionals, and functions. When you open a terminal, you are interacting with a shell process. You can check your current shell with echo $SHELL.

Open this question on its own page
04

What is the difference between Linux and Unix?

Unix is a proprietary OS developed at Bell Labs in the 1970s, while Linux is a free, open-source Unix-like OS kernel written from scratch by Linus Torvalds. Unix is certified and sold commercially (e.g., AIX, HP-UX, Solaris), whereas Linux is freely available under the GPL license. Both share the same design philosophy — everything is a file, small single-purpose tools, pipes — but Linux was not derived from Unix source code. Today, macOS is also Unix-certified (based on BSD). Linux dominates servers, cloud, and embedded systems due to its open nature and community development.

Open this question on its own page
05

How do you list files and directories in Linux?

Use the ls command to list files and directories. ls alone shows files in the current directory. Common options: ls -l shows a long listing with permissions, owner, size, and date; ls -a shows hidden files (those starting with a dot); ls -lh shows human-readable file sizes; ls -R lists recursively; ls -lt sorts by modification time. Example: ls -lah /var/log lists all files in /var/log with human-readable sizes including hidden ones.

Open this question on its own page
06

How do you change directory in Linux?

Use the cd (change directory) command. cd /path/to/dir moves to an absolute path. cd dirname moves into a subdirectory relative to the current location. cd .. moves up one level. cd ~ or just cd moves to your home directory. cd - returns to the previous directory. Example: cd /var/www/html navigates to the web root. The current directory is always represented by . and the parent by ...

Open this question on its own page
07

How do you display the current working directory?

Use the pwd (print working directory) command. It outputs the full absolute path of the directory you are currently in. For example, if you are in your home folder it prints /home/username. The -P flag resolves symbolic links and prints the physical path. The current directory is also stored in the $PWD environment variable, so echo $PWD gives the same result. This is useful in scripts to determine the script's working context.

Open this question on its own page
08

How do you create a new directory?

Use the mkdir command. mkdir dirname creates a single directory. mkdir -p path/to/nested/dir creates the full path including all intermediate directories — the -p flag is very useful and prevents errors if the directory already exists. mkdir -m 755 dirname creates a directory with specific permissions. To create multiple directories at once: mkdir dir1 dir2 dir3. Example: mkdir -p /var/app/logs/2026 creates all directories in the chain.

Open this question on its own page
09

How do you remove a file in Linux?

Use the rm command. rm filename deletes a file. rm -f filename forces deletion without prompting. rm -r dirname recursively deletes a directory and all its contents. rm -rf dirname is a common but dangerous combination — it force-deletes recursively with no confirmation. To remove an empty directory, use rmdir dirname. Always double-check paths before using rm -rf as there is no recycle bin — deleted files are gone immediately.

Open this question on its own page
10

How do you copy a file in Linux?

Use the cp command. cp source destination copies a file. cp -r source_dir dest_dir copies a directory recursively. cp -p preserves file attributes (timestamps, permissions, ownership). cp -i prompts before overwriting. cp -u only copies if the source is newer than the destination. Example: cp -rp /etc/nginx /backup/nginx_backup copies the Nginx config directory preserving all attributes.

Open this question on its own page
11

How do you move or rename a file in Linux?

Use the mv command for both moving and renaming. mv oldname newname renames a file within the same directory. mv file /new/path/ moves the file to a new location. mv -i prompts before overwriting existing files. mv -u only moves if the source is newer. Unlike cp, mv does not need a -r flag for directories — it moves them atomically if on the same filesystem. Cross-filesystem moves copy then delete the original.

Open this question on its own page
12

How do you view the contents of a file?

Several commands display file contents. cat filename prints the entire file. less filename shows it page by page (press q to quit, / to search) — preferred for large files. more filename is an older pager. head -n 20 filename shows the first 20 lines. tail -n 20 filename shows the last 20 lines. tail -f filename follows the file in real time — essential for log monitoring. tac filename prints lines in reverse order.

Open this question on its own page
13

What is the difference between absolute and relative paths?

An absolute path starts from the root directory / and fully specifies the location of a file regardless of the current directory, e.g., /home/user/docs/report.txt. A relative path is specified relative to the current working directory, e.g., docs/report.txt or ../sibling/file. Absolute paths are unambiguous and safe to use in scripts. Relative paths are shorter and useful for portable references within a project. The special tokens . (current dir) and .. (parent dir) are used only in relative paths.

Open this question on its own page
14

How do you display the manual for a command?

Use the man command followed by the command name, e.g., man ls. Man pages are divided into numbered sections: section 1 is user commands, section 2 is system calls, section 5 is file formats, section 8 is admin commands. Specify a section with man 5 passwd. Within the man pager, use arrow keys or j/k to scroll, / to search, and q to quit. man -k keyword (or apropos keyword) searches all man page descriptions. --help or -h flags on most commands also give quick usage summaries.

Open this question on its own page
15

What is the root directory in Linux?

The root directory (/) is the top-level directory in the Linux filesystem hierarchy — all files and directories reside under it. It is not to be confused with root user's home directory which is /root. The Filesystem Hierarchy Standard (FHS) defines the layout: /bin (essential binaries), /etc (configuration files), /var (variable data/logs), /home (user home directories), /tmp (temporary files), /usr (user programs), /proc (virtual process filesystem), /dev (device files).

Open this question on its own page
16

What is the home directory?

The home directory is a user-specific directory where personal files, configurations, and scripts are stored. For regular users it is typically /home/username; for the root user it is /root. The tilde ~ is a shell shortcut that expands to the current user's home directory. ~username expands to another user's home. Environment variables $HOME also points to the home directory. Configuration files (dotfiles like .bashrc, .profile, .ssh/) are stored here. Permissions on home directories are typically set to 700 or 750.

Open this question on its own page
17

How do you create a new file in Linux?

Several methods exist. touch filename creates an empty file or updates the timestamp of an existing one. echo "content" > filename creates a file with content (overwrites if exists). echo "content" >> filename appends to a file. cat > filename lets you type content interactively (Ctrl+D to save). Text editors like nano filename, vim filename, or gedit filename also create files on save. printf "line1\nline2\n" > filename writes formatted content.

Open this question on its own page
18

What is the difference between / and ~ in Linux?

/ is the root directory — the top of the entire filesystem hierarchy. All files and directories on the system live under /. ~ is a shell shortcut for the current user's home directory, which is typically /home/username (or /root for the root user). Running cd / takes you to the system root, while cd ~ or just cd takes you to your personal home directory. In scripts, always use $HOME instead of ~ as tilde expansion is not guaranteed in all contexts.

Open this question on its own page
19

How do you check disk usage in Linux?

Use df (disk free) and du (disk usage). df -h shows overall disk space usage for all mounted filesystems in human-readable form (GB/MB). df -hT also shows filesystem type. du -sh /path shows total size of a directory. du -sh * shows sizes of all items in the current directory. du -h --max-depth=1 /var gives a summary one level deep. For a visual overview, tools like ncdu (interactive) are very helpful. High disk usage on /var/log is a common production issue.

Open this question on its own page
20

How do you check memory usage in Linux?

Use free -h to display RAM and swap usage in human-readable format. The output shows total, used, free, shared, buff/cache, and available memory. Available (not Free) is the realistic amount usable by new processes since Linux aggressively uses RAM for caching. cat /proc/meminfo shows detailed memory statistics. vmstat -s gives a summary. top and htop show per-process memory usage in real time. For a single number: free -m | awk '/^Mem/ {print $3}' gives used MB.

Open this question on its own page
21

How do you view running processes in Linux?

ps aux shows a snapshot of all running processes with CPU%, memory%, PID, and command. ps aux | grep processname filters for a specific process. top provides a real-time dynamic view of processes sorted by CPU usage — press M to sort by memory, k to kill a process by PID. htop (if installed) is a more user-friendly interactive version of top with color and mouse support. pgrep processname returns the PID of matching processes. pstree shows processes in a tree hierarchy.

Open this question on its own page
22

How do you kill a process in Linux?

Use the kill command with a PID. kill PID sends SIGTERM (signal 15) — a graceful termination request. kill -9 PID sends SIGKILL — forces immediate termination and cannot be caught or ignored. Find PID with ps aux | grep name or pgrep name. pkill processname kills by name without needing the PID. killall processname kills all processes with that name. Use SIGTERM first and only escalate to SIGKILL if the process doesn't respond, as SIGKILL doesn't allow cleanup.

Open this question on its own page
23

What are file permissions in Linux?

Linux uses a Unix permission model with three permission classes: owner (user), group, and others. Each class has three bits: read (r=4), write (w=2), and execute (x=1). In ls -l output, permissions appear as a 10-character string like -rwxr-xr--: first char is file type (- file, d directory, l symlink), then 3 chars each for owner, group, others. Octal notation: 755 = owner rwx, group r-x, others r-x. Execute permission on a directory means the ability to enter it.

Open this question on its own page
24

How do you change file permissions?

Use chmod (change mode). In octal mode: chmod 755 file sets owner=rwx, group=r-x, others=r-x. In symbolic mode: chmod u+x file adds execute for owner; chmod g-w file removes write for group; chmod o=r file sets others to read-only; chmod a+x file adds execute for all. chmod -R 644 /dir applies recursively. Common patterns: 600 for private keys (owner read/write only), 644 for web files, 755 for directories and executables, 777 is insecure and should be avoided.

Open this question on its own page
25

What does chmod 755 mean?

chmod 755 sets permissions using octal notation. Each digit represents a class: 7 = owner (4+2+1 = read+write+execute), 5 = group (4+0+1 = read+execute), 5 = others (4+0+1 = read+execute). So the owner can read, write, and execute; group and others can only read and execute — they cannot modify the file. This is the standard permission for executable files and directories. In symbolic form it is rwxr-xr-x. It is appropriate for web server directories, system scripts, and any file that should be executable by all but only writable by the owner.

Open this question on its own page
26

What is the difference between chmod and chown?

chmod (change mode) changes the permission bits of a file — what actions are allowed for owner, group, and others. chown (change owner) changes the ownership of a file — who the owner and group are. Example: chown www-data:www-data /var/www/html sets both user and group ownership. chown user file changes only the user owner. chown :group file changes only the group. chown -R user:group /dir changes ownership recursively. Only root (or the file owner for chmod) can change these attributes. Both often need to be used together when deploying applications.

Open this question on its own page
27

How do you find a file in Linux?

Use the find command. find /path -name "filename" searches by exact name. find /path -name "*.log" uses a wildcard. find / -type f -name "config.php" finds files (not dirs). find / -type d -name "logs" finds directories. find /home -user john finds files owned by john. find /tmp -mtime +7 finds files modified more than 7 days ago. locate filename is faster (uses a database updated by updatedb) but may not reflect recent changes. which command finds the path of an executable in your PATH.

Open this question on its own page
28

How do you search for text within files?

Use grep (global regular expression print). grep "pattern" filename searches a single file. grep -r "pattern" /dir searches recursively in a directory. grep -i makes the search case-insensitive. grep -n shows line numbers. grep -l shows only filenames with matches. grep -v inverts — shows lines that do NOT match. grep -c counts matching lines. For multiple files: grep "error" /var/log/*.log. egrep or grep -E enables extended regular expressions. fgrep or grep -F treats the pattern as a literal string (faster).

Open this question on its own page
29

What is a symbolic link?

A symbolic link (symlink or soft link) is a special file that points to another file or directory by its path — like a shortcut in Windows. It contains only the path to the target, not the data itself. If the target is deleted or moved, the symlink becomes dangling (broken). Create with: ln -s /original/path /link/path. Symlinks show as lrwxrwxrwx in ls -l with an arrow indicating the target. They can cross filesystems and partitions. Common use: /usr/bin/python symlinking to python3, or versioned library files.

Open this question on its own page
30

How do you create a symbolic link?

Use ln -s target link_name. The -s flag creates a symbolic (soft) link. Without -s, a hard link is created. Example: ln -s /var/www/html/current /var/www/html/latest. To link a binary: ln -s /usr/local/bin/python3.11 /usr/local/bin/python3. Use absolute paths for the target when the link might be accessed from different directories. ls -la shows the symlink and where it points. To remove a symlink: rm linkname (do NOT use rm -r on a symlink to a directory — it may delete the target contents).

Open this question on its own page
31

What is the difference between a hard link and a soft link?

A hard link is a direct directory entry pointing to the same inode as the original file — both names refer to the exact same data on disk. Deleting one doesn't affect the other because the data persists as long as any hard link exists. Hard links cannot cross filesystems and cannot link to directories. A soft link (symlink) is a file containing a path to the target — it's an indirect reference. If the target is deleted, the symlink breaks. Symlinks can cross filesystems and link to directories. Check inode numbers with ls -li — hard links share the same inode number.

Open this question on its own page
32

How do you display the last few lines of a file?

Use tail filename which shows the last 10 lines by default. tail -n 50 filename shows the last 50 lines. tail -f filename (follow mode) continuously streams new content as it is appended — invaluable for monitoring log files in real time (e.g., tail -f /var/log/nginx/access.log). tail -F filename is like -f but also handles log rotation by reopening the file if it is recreated. Combine with grep: tail -f app.log | grep ERROR to filter real-time log output.

Open this question on its own page
33

How do you display the first few lines of a file?

Use head filename which shows the first 10 lines by default. head -n 20 filename shows the first 20 lines. head -c 100 filename shows the first 100 bytes. Useful for inspecting large files, checking CSV headers, or verifying the start of log files. Combine with other commands: cat /etc/passwd | head -5 shows only the first 5 lines of passwd. In scripts, head -1 file extracts the first line (e.g., reading a config value or CSV header).

Open this question on its own page
34

What is a shell script?

A shell script is a text file containing a sequence of shell commands that are executed in order by a shell interpreter (such as Bash). Scripts automate repetitive tasks, system administration, deployments, backups, and more. A script starts with a shebang line (e.g., #!/bin/bash) that tells the OS which interpreter to use. Scripts support variables, conditionals, loops, functions, and command substitution — making them a full programming environment. They are widely used for DevOps automation, cron jobs, and system configuration management.

Open this question on its own page
35

How do you run a shell script?

Three main ways: (1) Make it executable and run directly: chmod +x script.sh then ./script.sh. (2) Pass it as an argument to the interpreter: bash script.sh or sh script.sh — this works even without the executable bit or shebang. (3) Source it (run in the current shell): source script.sh or . script.sh — this shares the script's environment (variables) with the calling shell, unlike methods 1 and 2 which run in a subprocess. Use sourcing for scripts that set environment variables (like activating a virtualenv or loading secrets).

Open this question on its own page
36

What is the shebang line?

The shebang (or hashbang) is the first line of a script: #!/path/to/interpreter. The #! tells the OS kernel which program should execute the script. Common examples: #!/bin/bash for Bash scripts, #!/bin/sh for POSIX-compatible scripts, #!/usr/bin/env python3 for Python (using env to find the interpreter in PATH — more portable). Without a shebang, the kernel defaults to /bin/sh. The shebang is only meaningful when the script is executed directly (not when passed to an interpreter explicitly). Always include a shebang for clarity and portability.

Open this question on its own page
37

How do you make a script executable?

Use chmod +x scriptname.sh to add execute permission for the owner (and group/others based on umask). More specific: chmod u+x script.sh (owner only), chmod 755 script.sh (owner rwx, others r-x). After that, run it with ./script.sh (the ./ prefix is required to run executables in the current directory, since . is typically not in PATH for security reasons). Scripts with proper shebangs can also be placed in a directory listed in $PATH (like /usr/local/bin/) to be callable by name from anywhere.

Open this question on its own page
38

What are environment variables?

Environment variables are named values stored in a process's environment that affect behavior of running processes and shells. They are inherited by child processes. Common ones: PATH (directories searched for executables), HOME (home directory), USER (current username), SHELL (current shell), PWD (current directory), LANG (locale), TERM (terminal type). Set a variable: export VAR=value. The export keyword makes it available to child processes. Without export, it's a local shell variable only. Applications use env vars for configuration (e.g., DATABASE_URL, API_KEY).

Open this question on its own page
39

How do you display environment variables?

printenv prints all environment variables. printenv VARNAME prints a specific variable's value. env also lists all environment variables. echo $VARNAME prints a specific variable (e.g., echo $PATH). set shows all shell variables (including local ones not in the environment). declare -p shows all declared variables with their attributes. To see the environment of a running process: cat /proc/PID/environ | tr '\0' '\n'. Use export -p to see all exported variables in a format that can be re-used in another shell.

Open this question on its own page
40

What is the purpose of the PATH variable?

PATH is a colon-separated list of directories that the shell searches when you type a command name without a full path. For example, if PATH=/usr/bin:/usr/local/bin:/bin, typing ls causes the shell to look for an executable named ls in each directory in order until it finds one. Add a directory: export PATH="$PATH:/new/dir". Permanently add it in ~/.bashrc or ~/.profile. The shell command which ls shows which PATH entry provides a given command. Security note: never put . (current directory) in PATH as it creates command injection risks.

Open this question on its own page
41

What does the echo command do?

echo prints text or variable values to standard output. echo "Hello World" prints the string. echo $HOME prints the HOME variable value. echo -n "text" suppresses the trailing newline. echo -e "line1\nline2" interprets escape sequences like \n (newline), \t (tab). echo * acts like ls (glob expansion). In scripts, echo is used for output, debugging, and writing to files with redirection: echo "config=true" >> config.txt. For more complex formatting, printf is more reliable and POSIX-portable.

Open this question on its own page
42

How do you use the history command?

history displays a numbered list of previously executed commands. history 20 shows the last 20 commands. Re-run a command by number: !42 runs command 42. !! repeats the last command (useful with sudo !! when you forgot sudo). !string runs the most recent command starting with that string. Press Ctrl+R for interactive reverse search through history. The history is stored in ~/.bash_history. history -c clears the in-memory history. HISTSIZE controls how many commands are remembered; HISTFILESIZE controls the file size.

Open this question on its own page
43

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

Single quotes (') preserve the literal value of every character — no variable expansion, no command substitution, no escape sequences. Everything inside is treated as plain text. Double quotes (") allow variable expansion ($VAR), command substitution ($(cmd)), and some escape sequences (\n, \"). Example: echo '$HOME' prints $HOME literally, while echo "$HOME" prints /home/user. Always double-quote variables in scripts ("$var") to prevent word splitting and globbing on values with spaces or special characters.

Open this question on its own page
44

How do you use wildcards (globbing) in Linux?

Shell wildcards (globs) expand to match filenames. * matches any sequence of characters (except leading dots): ls *.txt lists all .txt files. ? matches any single character: ls file?.txt matches file1.txt, fileA.txt. [abc] matches any one character in the set: ls [abc]*.sh. [0-9] matches any digit. {jpg,png,gif} is brace expansion (not globbing) matching listed alternatives: cp *.{jpg,png} /backup/. Globbing is done by the shell before passing arguments to commands. Use quotes to prevent glob expansion when passing patterns to tools like find or grep.

Open this question on its own page
Intermediate 31 questions

Practical knowledge for developers with hands-on experience.

01

What is piping in Linux?

Piping connects the standard output (stdout) of one command to the standard input (stdin) of another using the | operator. This allows chaining multiple commands to process data in a pipeline. Example: ps aux | grep nginx | awk '{print $2}' — lists processes, filters for nginx, then extracts PIDs. Pipes are created by the kernel as in-memory buffers; data flows left to right. All commands in a pipeline run concurrently. The exit status of a pipeline is the exit status of the last command (unless set -o pipefail is enabled, which makes it the status of the last failing command — important for robust scripts).

Open this question on its own page
02

What is I/O redirection in Linux?

Redirection changes the source or destination of standard streams. command > file redirects stdout to a file (overwrites). command >> file appends stdout to a file. command < file redirects a file to stdin. command 2> error.log redirects stderr (FD 2) to a file. command > all.log 2>&1 redirects both stdout and stderr to the same file (2>&1 merges stderr into stdout). command &> file is shorthand for the above in bash. command 2>/dev/null discards errors. /dev/null is the null device — anything written to it is discarded.

Open this question on its own page
03

What is the difference between > and >> in shell redirection?

> is the overwrite redirect operator. It creates the file if it doesn't exist, or truncates it to zero bytes before writing. This is destructive — existing content is lost. >> is the append redirect operator. It creates the file if it doesn't exist, or adds new content to the end of an existing file without destroying current content. Example: echo "start" > log.txt creates/overwrites; echo "more" >> log.txt appends. In scripts, use >> for logging to avoid accidentally wiping log files. Use : > file or truncate -s 0 file to explicitly empty a file.

Open this question on its own page
04

What are stdin, stdout, and stderr?

Every Linux process has three default file descriptors (FDs): stdin (FD 0) — standard input, the default source of input (keyboard by default). stdout (FD 1) — standard output, where normal output goes (terminal by default). stderr (FD 2) — standard error, where error messages go (also terminal by default but separate from stdout). This separation lets you redirect output and errors independently: command > out.txt 2> err.txt. Programs like ls write filenames to stdout and error messages ("No such file") to stderr. In pipelines, only stdout flows through the pipe unless you merge with 2>&1.

Open this question on its own page
05

How do you use grep effectively?

grep is one of the most powerful text-processing tools. Key flags: -i (case-insensitive), -r (recursive), -n (show line numbers), -l (filenames only), -c (count matches), -v (invert match), -w (whole word), -A 3 (3 lines after match), -B 3 (3 lines before), -C 3 (3 lines context). Use grep -E for extended regex: grep -E "error|warning" app.log. Combine: grep -rn "TODO" src/ | grep -v ".git". grep -P enables Perl-compatible regex (PCRE) for lookaheads and other advanced patterns. Performance tip: grep -F for literal strings is faster than regex.

Open this question on its own page
06

What are regular expressions and how are they used in Linux?

Regular expressions (regex) are patterns for matching text. In Linux they're used in grep, sed, awk, and many other tools. Key metacharacters: . (any char), * (zero or more), + (one or more, ERE), ? (zero or one, ERE), ^ (start of line), $ (end of line), [] (character class), [^] (negated class), {n,m} (repetition), () (grouping/capturing), | (alternation). BRE (basic) vs ERE (extended — use grep -E or egrep). Example: grep -E "^[0-9]{1,3}(\.[0-9]{1,3}){3}$" matches IPv4 addresses. Always test regex with grep --color to highlight matches.

Open this question on its own page
07

How do you use sed for text processing?

sed (stream editor) processes text line by line. Most common use: substitution: sed 's/old/new/' file replaces the first occurrence per line; sed 's/old/new/g' replaces all. sed -i 's/foo/bar/g' file edits the file in-place (add a backup suffix: sed -i.bak). Delete lines: sed '/pattern/d' file. Print specific lines: sed -n '5,10p' file. Insert before a line: sed '/pattern/i\new line'. Append after: sed '/pattern/a\new line'. Multiple expressions: sed -e 's/a/b/' -e 's/c/d/'. Use sed -n to suppress default output and only print explicitly with p.

Open this question on its own page
08

How do you use awk for text processing?

awk is a pattern-scanning and processing language. It processes input record by record (default: line by line) and splits each into fields (default: whitespace-separated). $1, $2, etc. refer to fields; $0 is the whole line; NF is number of fields; NR is line number. Example: awk '{print $1, $3}' file prints fields 1 and 3. Filter: awk '/pattern/ {print $2}' file. Arithmetic: awk '{sum += $1} END {print sum}' numbers.txt. Custom delimiter: awk -F: '{print $1}' /etc/passwd prints usernames. BEGIN and END blocks run before/after all input. awk is excellent for structured data like CSVs and log files.

Open this question on its own page
09

What is a daemon in Linux?

A daemon is a background process that runs continuously to provide services, typically started at boot and not tied to any user session. Daemon names often end in d: sshd (SSH server), nginx (web server), crond (cron scheduler), systemd. Daemons have no controlling terminal (TTY is ? in ps output). They typically detach from the terminal by forking and calling setsid(). Modern daemons are managed by systemd: systemctl start/stop/status/enable servicename. journalctl -u servicename views daemon logs. Daemons differ from regular background processes (command &) in their persistence and service-oriented nature.

Open this question on its own page
10

What are file descriptors in Linux?

A file descriptor (FD) is a non-negative integer that uniquely identifies an open file (or socket, pipe, device) within a process. The OS kernel maintains a file descriptor table per process. FD 0 = stdin, FD 1 = stdout, FD 2 = stderr. Additional FDs are allocated starting from 3. In shell scripts, you can open custom FDs: exec 3> output.txt opens FD 3 for writing; echo "data" >&3 writes to it; exec 3>&- closes it. View a process's open FDs: ls -la /proc/PID/fd/. The limit of open FDs per process is controlled by ulimit -n (default 1024; commonly raised to 65535+ for high-performance servers).

Open this question on its own page
11

How do you schedule jobs with cron?

cron is a time-based job scheduler. Jobs are defined in a crontab file. Edit with: crontab -e. Each line has the format: minute hour day month weekday command. Values: * = any, */5 = every 5, 1-5 = range, 1,3,5 = list. Examples: 0 2 * * * /backup.sh (daily at 2am), */15 * * * * /check.sh (every 15 min), 0 9 * * 1 /report.sh (Monday 9am). crontab -l lists current jobs. System-wide crons are in /etc/crontab and /etc/cron.d/. Always use full paths in cron commands since PATH is limited. Redirect output to a log: command >> /var/log/job.log 2>&1.

Open this question on its own page
12

How do you set up SSH key authentication?

SSH key authentication uses asymmetric cryptography to authenticate without passwords. Steps: (1) Generate a key pair on the client: ssh-keygen -t ed25519 -C "your_email" (or RSA: -t rsa -b 4096). This creates ~/.ssh/id_ed25519 (private) and ~/.ssh/id_ed25519.pub (public). (2) Copy the public key to the server: ssh-copy-id user@server (or manually append to ~/.ssh/authorized_keys on the server). (3) Ensure server permissions: ~/.ssh must be 700, authorized_keys must be 600. (4) Optionally disable password auth in /etc/ssh/sshd_config: set PasswordAuthentication no. Use ssh-agent and ssh-add to avoid entering the passphrase repeatedly.

Open this question on its own page
13

How does rsync work and when do you use it?

rsync is a fast file synchronization tool that transfers only the differences (deltas) between source and destination, making it efficient for large directories. Common usage: rsync -avz /source/ user@remote:/dest/. Flags: -a (archive: preserves permissions, timestamps, symlinks, ownership), -v (verbose), -z (compress during transfer), --delete (remove files at destination that no longer exist at source), --dry-run (preview without making changes), --exclude='*.log' (skip patterns), --progress (show per-file progress). Unlike scp, rsync resumes interrupted transfers. It is the standard tool for backups, deployments, and server migrations.

Open this question on its own page
14

What are subshells in bash?

A subshell is a child process created by the current shell. It inherits copies of the parent's variables and environment but any changes to variables or the working directory in the subshell do NOT affect the parent. Subshells are created by: (1) Parentheses grouping: (cd /tmp; ls) — changes directory only inside the subshell. (2) Command substitution: $(command). (3) Pipelines — each command in a pipe runs in a subshell. (4) Backgrounding with &. Check if you're in a subshell: echo $BASH_SUBSHELL (0 = parent, 1+ = subshell depth). This behavior is why source script.sh is needed to have a script's variable assignments affect the current shell.

Open this question on its own page
15

How do you pass arguments to a shell script?

Arguments are passed after the script name: ./script.sh arg1 arg2 arg3. Inside the script, access them via positional parameters: $1 is the first argument, $2 second, etc. $0 is the script name itself. $# is the count of arguments. $@ is all arguments as separate words (preserves quoting when quoted: "$@"). $* is all arguments as a single word. Always use "$@" (quoted) when passing arguments to another command to handle arguments with spaces correctly. Use shift to shift positional parameters left. getopts handles option parsing (-f value style flags).

Open this question on its own page
16

What are special variables in bash?

Bash has several special variables with predefined meanings: $0 — script/shell name; $1-$9 — positional arguments; $# — argument count; $@ — all args as separate words; $* — all args as one word; $? — exit status of the last command (0=success, non-zero=failure); $$ — PID of the current shell; $! — PID of the last background process; $_ — last argument of the previous command; $- — current shell option flags; $IFS — Internal Field Separator (default: space/tab/newline). Understanding these is essential for robust scripting and error handling.

Open this question on its own page
17

How do you use arrays in bash?

Bash supports indexed arrays (0-based). Declare: arr=(one two three) or declare -a arr. Access: ${arr[0]} (first element), ${arr[@]} (all elements), ${arr[*]} (all as one string). Length: ${#arr[@]}. Append: arr+=(four). Modify: arr[1]="TWO". Iterate: for item in "${arr[@]}"; do echo "$item"; done. Slice: ${arr[@]:1:2} (elements 1 and 2). Delete element: unset arr[2]. Array from command: files=($(ls *.txt)) — but better: mapfile -t files < <(ls *.txt) to handle filenames with spaces safely.

Open this question on its own page
18

How do you write conditional statements in bash?

Bash uses if/elif/else/fi for conditionals. Syntax: if [ condition ]; then ... elif [ condition ]; then ... else ... fi. Common test operators: -eq/-ne/-lt/-gt (numeric), ==/!= (string), -z (string empty), -n (string not empty), -f (file exists), -d (directory exists), -r/-w/-x (readable/writable/executable). The [[ ]] construct (bash-specific) is preferred: supports &&/|| directly, pattern matching with =~, and avoids word-splitting issues. Short-circuit: command && echo ok runs second only if first succeeds; command || echo fail runs second only if first fails.

Open this question on its own page
19

How do you write loops in bash?

Bash supports three loop types. for loop: for i in 1 2 3; do echo $i; done or C-style for ((i=0; i<10; i++)); do ... done. while loop: while [ condition ]; do ... done — commonly used to read files line by line: while IFS= read -r line; do echo "$line"; done < file.txt. until loop: runs until condition becomes true — opposite of while. Loop controls: break exits the loop, continue skips to the next iteration. Iterate over files: for f in *.txt; do process "$f"; done. Always quote loop variables to handle filenames with spaces.

Open this question on its own page
20

What is the difference between [ ] and [[ ]] in bash?

[ ] is the POSIX-standard test command (also /usr/bin/[). It has strict quoting requirements — unquoted variables with spaces cause word splitting and errors. [[ ]] is a bash keyword (not a command) with enhanced features: supports && and || directly, regex matching with =~, pattern matching with ==, no word splitting on unquoted variables, and more natural behavior overall. Example: [[ "$str" =~ ^[0-9]+$ ]] tests if string is all digits. Best practice: use [[ ]] in bash scripts for safety and power; use [ ] only when writing POSIX sh-compatible scripts. Arithmetic comparisons: use (( )) — e.g., ((x > 5)).

Open this question on its own page
21

How do you handle errors in shell scripts?

Key strategies: (1) Check $? after commands: if [ $? -ne 0 ]; then echo "Error"; exit 1; fi. (2) Use set -e at the top — exits the script on any command failure (use carefully; may exit prematurely). (3) set -u — treat unset variables as errors. (4) set -o pipefail — pipeline fails if any command in it fails (not just the last). (5) Combine: set -euo pipefail is a common "strict mode". (6) Use trap for cleanup on exit: trap 'rm -f /tmp/tempfile' EXIT. (7) Use || { echo "cmd failed"; exit 1; } pattern. Good error messages should include the line number ($LINENO) and context.

Open this question on its own page
22

What is the exit status of a command?

Every command returns an exit status (return code) between 0 and 255. 0 indicates success; non-zero indicates failure. The exit status of the last command is stored in $?. Common conventions: 1 = general error, 2 = misuse of shell builtin, 126 = command not executable, 127 = command not found, 128+N = killed by signal N (e.g., 130 = Ctrl+C which is SIGINT = signal 2, so 128+2=130). Scripts can return a custom exit code with exit N. Functions return status with return N. Always check exit statuses in production scripts. Tools like grep return 0 if match found, 1 if no match, 2 on error.

Open this question on its own page
23

How do you define and use functions in bash?

Bash functions are defined as: function_name() { commands; } or function function_name { commands; }. Call with just: function_name arg1 arg2. Inside, arguments are accessed as $1, $2, etc. (separate from script-level positional params). Functions share the shell's variable scope by default. Use local varname to create local variables that don't leak out. Functions return exit codes via return N (not values — for values, use echo and capture with $()). Best practice: define all functions before calling them. Functions enable code reuse, testing, and cleaner scripts. Example: log() { echo "[$(date)] $*" >> app.log; }

Open this question on its own page
24

What is command substitution in bash?

Command substitution captures the output of a command and inserts it into another command or variable assignment. Modern syntax: $(command) — preferred. Legacy syntax: `command` (backticks) — avoid, as backticks don't nest well. Examples: today=$(date +%Y-%m-%d) stores the current date. files=$(ls *.txt) stores filenames. echo "You are $(whoami)". Nesting: $(outer $(inner)). The output has trailing newlines stripped. Be careful with filenames containing spaces — always quote: file="$(find . -name '*.conf' | head -1)". Command substitution creates a subshell, so variable changes inside don't affect the parent shell.

Open this question on its own page
25

How do you use the xargs command?

xargs builds and executes commands from standard input. It takes lines or items from stdin and passes them as arguments to a command. Basic: find . -name "*.tmp" | xargs rm — deletes all .tmp files. -I {} specifies a placeholder: find . -name "*.jpg" | xargs -I {} cp {} /backup/. -P 4 runs up to 4 processes in parallel. -n 1 passes one argument per command invocation. -0 uses null byte as delimiter (pairs with find -print0) for safe handling of filenames with spaces: find . -name "*.log" -print0 | xargs -0 rm. Without -0, filenames with spaces will be split incorrectly.

Open this question on its own page
26

What is the tr command used for?

tr (translate) reads from stdin and replaces or deletes individual characters. tr 'a-z' 'A-Z' converts lowercase to uppercase. tr 'A-Z' 'a-z' does the reverse. tr -d '\n' deletes all newlines (joins all lines into one). tr -d '[:space:]' removes all whitespace. tr -s ' ' squeezes multiple spaces into one. echo "hello" | tr '[a-m]' '[A-M]'. Common use: cat file | tr ',' '\n' converts CSV commas to newlines. tr only works on single characters, not strings — use sed for multi-character replacements. It's very fast for character-level transformation of large files.

Open this question on its own page
27

How do you use the cut command?

cut extracts specific columns or fields from each line of input. cut -d',' -f1,3 file.csv extracts fields 1 and 3 from a comma-delimited file. -d sets the delimiter, -f selects field numbers (1-based). cut -c1-10 file extracts characters 1 through 10. cut -d':' -f1 /etc/passwd lists all usernames. -f2- means from field 2 to end; -f-3 means from start to field 3. For files with irregular whitespace, awk is more robust. cut is POSIX-standard, fast, and great for structured data like logs with consistent delimiters.

Open this question on its own page
28

What is the difference between fg, bg, and & in bash?

& at the end of a command runs it in the background (a background job): long_command &. The shell immediately returns a prompt. bg resumes a suspended (Ctrl+Z) job in the background: bg %1 where %1 is the job number. fg brings a background or suspended job to the foreground: fg %1. jobs lists all current jobs with their numbers and status (running/stopped). Ctrl+Z suspends the foreground process (sends SIGTSTP). Ctrl+C terminates it (sends SIGINT). Background jobs may output to the terminal unexpectedly — redirect their output: cmd > output.log 2>&1 &.

Open this question on its own page
29

How do you use find with -exec?

find with -exec runs a command on each matched file. Syntax: find /path -name "*.log" -exec command {} \; — the {} is replaced by the filename, and \; terminates the -exec expression (each file gets its own command invocation). Faster alternative: -exec command {} + — appends all filenames to one command invocation (like xargs). Example: find /tmp -mtime +30 -exec rm {} + deletes files older than 30 days. find . -type f -name "*.php" -exec grep -l "TODO" {} \; finds PHP files containing TODO. Combine with -not, -and, -or for complex filters.

Open this question on its own page
30

What is the difference between source and executing a script?

When you execute a script (./script.sh or bash script.sh), a new child process (subshell) is created. Variables set in the script, directory changes, and function definitions do NOT persist in the calling shell after it finishes. When you source a script (source script.sh or . script.sh), the script runs in the current shell process — all variable assignments, function definitions, and cd commands affect the current environment. Sourcing is essential for configuration files (~/.bashrc), loading environment variables, activating virtual environments, and defining shell functions you want to use interactively.

Open this question on its own page
31

How do you debug a shell script?

Several techniques: (1) bash -x script.sh — enables xtrace mode, printing each command with a + prefix before executing it. (2) Add set -x inside the script to enable tracing at a specific point; set +x to disable. (3) set -v prints each line as it is read (before expansion). (4) bash -n script.sh — syntax-checks the script without executing (dry run). (5) Add echo "DEBUG: var=$var" statements. (6) Use set -euo pipefail to catch errors early. (7) PS4='${BASH_SOURCE}:${LINENO}+ ' makes xtrace output include file and line number. Tools: shellcheck (static analysis), bashdb (interactive debugger).

Open this question on its own page
Advanced 17 questions

Deep expertise questions for senior and lead roles.

01

What is a named pipe (FIFO) in Linux?

A named pipe (FIFO) is a special file that provides inter-process communication (IPC) in a first-in-first-out manner. Unlike regular pipes (|) which only exist between related processes, named pipes exist as filesystem entries and allow unrelated processes to communicate. Create with: mkfifo /tmp/mypipe. Process A writes: echo "data" > /tmp/mypipe (blocks until a reader appears). Process B reads: cat /tmp/mypipe (blocks until data is written). Named pipes have no disk storage — data flows directly in memory. Use cases: streaming data between processes, avoiding temporary files, creating simple producer-consumer patterns. Clean up with rm /tmp/mypipe.

Open this question on its own page
02

How do Linux signals work?

Signals are software interrupts sent to processes to notify them of events. Common signals: SIGHUP (1) — terminal hangup, often used to reload config; SIGINT (2) — Ctrl+C, interrupt; SIGQUIT (3) — Ctrl+\, quit with core dump; SIGKILL (9) — forceful kill, cannot be caught or ignored; SIGTERM (15) — graceful termination, can be caught; SIGUSR1/2 — user-defined; SIGCHLD — child process changed state. Send with kill -SIGNAL PID. In bash, handle signals with trap: trap 'echo caught; cleanup' SIGTERM. SIGKILL and SIGSTOP can never be caught or blocked — they are handled by the kernel directly.

Open this question on its own page
03

What is process substitution in bash?

Process substitution lets you use the output of a command as if it were a file. Syntax: <(command) (output as file) or >(command) (input as file). The shell creates a named pipe or /dev/fd/N entry. Example: diff <(sort file1) <(sort file2) — diffs the sorted versions without creating temp files. comm <(sort a.txt) <(sort b.txt). Paste columns: paste <(cut -d: -f1 /etc/passwd) <(cut -d: -f6 /etc/passwd). Unlike command substitution ($()), process substitution doesn't capture output — it provides a file descriptor. It runs asynchronously, so be careful with exit codes — the substituted process's exit code is not captured by $?.

Open this question on its own page
04

How do you use trap in shell scripting?

trap registers a command to run when the shell receives a signal or exits. Syntax: trap 'commands' SIGNAL. Key use case — cleanup on exit: trap 'rm -f /tmp/lockfile; echo "Exiting"' EXIT. The EXIT pseudo-signal fires whenever the script exits (normally or due to error). Handle Ctrl+C gracefully: trap 'echo "Interrupted"; exit 130' INT. trap '' SIGTERM ignores SIGTERM. trap - SIGNAL resets to default behavior. trap is essential for: removing temp files, releasing locks, sending notifications on failure, and ensuring cleanup in long-running scripts. Always set up trap early in the script before resources are acquired.

Open this question on its own page
05

What is the difference between login and non-login shells?

A login shell is started when a user first logs in (via console, SSH, su -). It sources: /etc/profile, then the first of ~/.bash_profile, ~/.bash_login, or ~/.profile. A non-login shell is started when opening a terminal emulator or running bash directly. It sources /etc/bash.bashrc and ~/.bashrc. Common confusion: changes to ~/.bashrc don't take effect in SSH sessions unless ~/.bash_profile sources it (which it should: [ -f ~/.bashrc ] && . ~/.bashrc). Interactive vs non-interactive: interactive shells read from a terminal; non-interactive (scripts) don't. Check with $- containing i, or [[ $- == *i* ]].

Open this question on its own page
06

How does the Linux boot process work?

The Linux boot process: (1) BIOS/UEFI performs POST, locates the bootloader on the boot device. (2) Bootloader (GRUB2) loads the Linux kernel and initramfs into memory. (3) Kernel initialization: decompresses itself, initializes hardware, mounts the initial RAM filesystem (initramfs). (4) initramfs: provides a minimal root filesystem with tools to mount the real root filesystem (handles encryption, RAID, LVM). (5) Init process (PID 1): kernel starts systemd (or legacy SysV init). (6) systemd activates targets (runlevels): mounts filesystems, starts services, brings up networking, launches getty (login). The whole process is traceable with systemd-analyze blame and dmesg.

Open this question on its own page
07

What is systemd and how do you use it?

systemd is the init system and service manager used by most modern Linux distros. It replaces SysV init and uses unit files (in /etc/systemd/system/ or /lib/systemd/system/) to define services, mounts, timers, sockets, and more. Key commands: systemctl start/stop/restart/reload servicename, systemctl enable/disable servicename (enable = start at boot), systemctl status servicename, systemctl list-units --type=service. Logs: journalctl -u servicename -f (follow), journalctl -b (since last boot), journalctl --since "1 hour ago". Create a service unit file with [Unit], [Service], and [Install] sections. Run systemctl daemon-reload after changing unit files.

Open this question on its own page
08

What is the /proc filesystem?

/proc is a virtual filesystem (pseudo-filesystem) that provides a window into the kernel's internal state — it exists only in memory, not on disk. Each running process has a directory /proc/PID/ containing: cmdline (command line), environ (environment), fd/ (open file descriptors), maps (memory mappings), status (process state). Key system files: /proc/cpuinfo (CPU details), /proc/meminfo (memory stats), /proc/net/ (network stats), /proc/sys/ (kernel parameters tunable via sysctl). Example: sysctl -w net.ipv4.ip_forward=1 or echo 1 > /proc/sys/net/ipv4/ip_forward enables IP forwarding. Persist with /etc/sysctl.conf.

Open this question on its own page
09

How do you write robust, production-grade shell scripts?

Key practices for production scripts: (1) Strict mode: set -euo pipefail at the top. (2) Cleanup traps: trap 'rm -f "$tmpfile"' EXIT. (3) Use mktemp for temp files: tmpfile=$(mktemp). (4) Quote all variables: "$var", "$@". (5) Check dependencies: command -v jq &>/dev/null || { echo "jq required"; exit 1; }. (6) Atomic file writes: write to a temp file then mv to the target. (7) Locking: use flock to prevent concurrent runs. (8) Logging: timestamp all output. (9) Idempotency: safe to run multiple times. (10) Static analysis: run shellcheck before deploying. (11) Use absolute paths for all commands in cron/systemd contexts.

Open this question on its own page
10

What is the difference between bash and POSIX sh scripting?

POSIX sh is a standard defining a minimal, portable shell feature set — scripts with #!/bin/sh should use only POSIX features to run on any compliant system. Bash is a superset — it adds arrays, [[ ]], (( )), process substitution, brace expansion, local (POSIX-optional), FUNCNAME, BASH_SOURCE, regex with =~, mapfile/readarray, and more. Common portability pitfalls: == in [ ] (use = in POSIX), $( ) is POSIX (backticks portable too), {a,b} brace expansion is not POSIX. Use #!/bin/bash and bash features freely for scripts that only run on Linux systems. Use #!/bin/sh only when cross-platform portability (BSD, macOS, Alpine) matters.

Open this question on its own page
11

How do you implement file locking in shell scripts?

File locking prevents multiple instances of a script from running simultaneously. The most robust method is flock: exec 9>/var/lock/myscript.lock; flock -n 9 || { echo "Already running"; exit 1; }. The lock is automatically released when the script exits (even on crash) because the FD is closed. Alternative — lockfile with PID: create a file containing the PID; check if PID is still running on startup; clean up on exit via trap. Use mkdir as an atomic lock: mkdir /tmp/mylock 2>/dev/null || { echo "Locked"; exit 1; }mkdir is atomic on most filesystems. For distributed locking across servers, use Redis or a database. Always pair locks with trap ... EXIT for cleanup.

Open this question on its own page
12

How do you use associative arrays in bash?

Associative arrays (hash maps/dictionaries) are available in bash 4+. Declare with: declare -A map. Assign: map["key"]="value" or map=([key1]=val1 [key2]=val2). Access: ${map["key"]}. All keys: ${!map[@]}. All values: ${map[@]}. Length: ${#map[@]}. Check if key exists: [[ -v map["key"] ]]. Delete: unset map["key"]. Iterate: for k in "${!map[@]}"; do echo "$k = ${map[$k]}"; done. Common use: counting occurrences, caching results, mapping hostnames to IPs. Note: macOS ships bash 3.2 (no assoc arrays) — use brew install bash or choose a different approach for cross-platform scripts.

Open this question on its own page
13

What are here documents and here strings in bash?

A here document (heredoc) provides multi-line input to a command inline in a script. Syntax: command <. The delimiter (EOF) can be any word; the heredoc ends at a line containing exactly that word. Variables are expanded by default; use <<'EOF' to prevent expansion. <<-EOF strips leading tabs (not spaces). Example: ssh user@host <<'EOF'\nls -la\npwd\nEOF. A here string feeds a single string to a command's stdin: command <<< "string". Example: grep "pattern" <<< "$variable" or read a b c <<< "1 2 3". Heredocs are used for generating config files, SQL queries, and multi-line messages in scripts.

Open this question on its own page
14

How do you use strace and ltrace for debugging in Linux?

strace traces system calls made by a process. strace command runs and traces the command. strace -p PID attaches to a running process. strace -e trace=open,read,write filters specific syscalls. strace -f follows child processes. strace -o output.txt saves to file. strace -T shows time spent in each syscall. Useful for: debugging "permission denied" (which files?), "file not found" (which path?), slow processes (which syscall blocks?). ltrace traces library calls (libc functions like malloc, fopen). ltrace -p PID command. Together, strace and ltrace are powerful for black-box debugging without source code.

Open this question on its own page
15

What are Linux capabilities?

Linux capabilities break the traditional all-or-nothing superuser model by dividing root privileges into discrete units that can be granted independently. Examples: CAP_NET_BIND_SERVICE (bind to ports < 1024 without being root), CAP_SYS_PTRACE (trace processes), CAP_CHOWN (change file ownership), CAP_KILL (send signals to any process), CAP_NET_ADMIN (network configuration). Manage with: getcap /path/binary (view), setcap cap_net_bind_service+ep /usr/bin/node (grant). Useful for: running web servers on port 80 without root, containers with minimal privileges. View a process's capabilities: cat /proc/PID/status | grep Cap; decode with capsh --decode=HEX.

Open this question on its own page
16

How do you use brace expansion and parameter expansion in bash?

Brace expansion generates multiple strings: {a,b,c}a b c; {1..5}1 2 3 4 5; file{.bak,.old,.tmp}file.bak file.old file.tmp. Useful: mkdir -p app/{src,tests,docs}. Parameter expansion manipulates variable values: ${var:-default} (use default if unset/empty), ${var:=default} (assign default if unset), ${var:?error} (error if unset), ${var:+other} (use other if set). String operations: ${var#prefix} (strip shortest prefix), ${var##prefix} (strip longest), ${var%suffix} (strip shortest suffix), ${var%%suffix} (longest suffix), ${var/old/new} (replace first), ${var//old/new} (replace all), ${var^^} (uppercase), ${var,,} (lowercase), ${#var} (string length).

Open this question on its own page
17

What is the significance of IFS in bash?

IFS (Internal Field Separator) determines how bash splits words during word splitting and how read splits input into fields. Default value is space+tab+newline ($' \t\n'). When bash performs unquoted variable expansion, it splits on IFS characters. Change IFS to parse CSVs: IFS=',' read -ra fields <<< "a,b,c". Parse a colon-delimited string: IFS=':' read -ra parts <<< "$PATH". Temporarily change IFS: old=$IFS; IFS='|'; ...; IFS=$old. Critical: always reset IFS after changing, or use a subshell. The safety idiom while IFS= read -r line sets IFS to empty to prevent stripping of leading/trailing whitespace from each line — essential for correctly reading files line by line.

Open this question on its own page
Back to All Topics 92 questions total