---
tags:
- linux
- l1
- flashcard-deck
- bash-scripting
---
<!-- wiki:breadcrumb:start -->
[Portal](../../../../library/portal/index.md) | **Level:** [L1: Foundations](../../../../library/portal/levels.md) | **Topics:** [Bash / Shell Scripting](../../../../library/portal/topics.md) | **Domain:** Linux
<!-- wiki:breadcrumb:end -->

id	category	difficulty	tags	question	answer	source_path
bash/07b6dc8d3502	bash	easy	bash, commands, redirection	How do you append the output of a command to a file?	Using the >> operator.\n\nRemember: > overwrites the file, >> appends to it. Mnemonic: one arrow = one shot (overwrite), two arrows = add more.\n\nExample: echo 'new line' >> logfile.txt adds without destroying existing content. Use > only when you want a fresh file.	projects/knowledge/interview/bash/038-append-to-file.txt
bash/0a8700fcd06f	bash	easy	bash, scripting, permissions	How do you make a shell script executable?	Give it execute permission (e.g., chmod +x script.sh) and ensure it has a proper shebang (#!/bin/bash) if run by name.\n\nExample: #!/usr/bin/env bash is preferred over #!/bin/bash — env finds bash in $PATH for portability.\n\nName origin: 'sharp' (#) + 'bang' (!) = shebang. Also called hashbang.\n\nRemember: cut -d',' -f1 extracts the first comma-separated field. -d sets delimiter, -f selects fields. For complex parsing, prefer awk.	projects/knowledge/interview/bash/027-make-script-executable.txt
bash/12bbfdb962c0	bash	medium	bash, scripting, source	How do you run a script in the current shell environment?	Use the source command (or .) like source script.sh (runs the script in the current shell, so its environment changes persist).\n\nRemember: source script.sh (or . script.sh) runs in the current shell — variables and functions persist after execution. ./script.sh runs in a subshell — changes are lost.\n\nGotcha: sourcing a script that calls 'exit' will close your current terminal! Use 'return' in sourced scripts instead of 'exit.'	projects/knowledge/interview/bash/028-run-script-in-current-shell.txt
bash/158488006f18	bash	medium	bash	Generate 8 digit random number	shuf -i 10000000-99999999 -n 1\n\nExample: $RANDOM gives a random integer 0-32767. For larger ranges, use shuf, /dev/urandom, or openssl rand. shuf is the simplest for integer ranges.	projects/knowledge/interview/bash/020-generate-8-digit-random-number.txt
bash/1608eb5716f1	bash	medium	bash, control-flow, debugging, scripting	How do you debug shell scripts?	Answer depends on the language you are using for writing your scripts. If Bash is used for example then:\n\n  * Adding -x to the script I'm running in Bash\n  * Old good way of adding echo statements\n\nIf Python, then using pdb is very useful.\n\nRemember: for complex text processing, consider Python over bash. Bash excels at file operations and command orchestration; Python excels at data manipulation and error handling.	projects/knowledge/interview/bash/016-how-do-you-debug-shell-scripts.txt
bash/16911028970e	bash	medium	bash, networking, security	What command is used for security audits and network scanning?	nmap (Network Mapper). It discovers hosts, open ports, running services, and OS versions on a network. Common usage: `nmap -sV -sC <target>` for service detection with default scripts.\n\nExample: sed -i 's/old/new/g' file.txt replaces all occurrences in-place. -i flag edits the file directly (use -i.bak for backup).	projects/knowledge/interview/bash/043-nmap-command.txt
bash/1a6db7cae0ea	bash	easy	bash	What is the ternary operator? How do you use it in bash?	"A short way of using if/else. An example:\n\n[[ $a = 1 ]] && b=""yes, equal"" || b=""nope""\n\nGotcha: bash scripts should start with set -euo pipefail for strict error handling. Without it, errors silently continue, producing wrong results."	projects/knowledge/interview/bash/021-what-is-the-ternary-operator-how-do-you-use-it-in-.txt
bash/1c9a83a1b845	bash	medium	bash, scripting, variables	What does ${VAR:=VALUE} accomplish?	It assigns VALUE to VAR only if VAR is unset or null.\n\nGotcha: bash scripts should start with set -euo pipefail for strict error handling. Without it, errors silently continue, producing wrong results.	projects/knowledge/interview/bash/027-default-value-assignment.txt
bash/1ea8c33c99cd	bash	easy	bash, background, jobs	How do you run a command in the background in Bash?	Append an ampersand (&) to the command (e.g., ./long_task & runs long_task in the background).\n\nGotcha: bash scripts should start with set -euo pipefail for strict error handling. Without it, errors silently continue, producing wrong results.	projects/knowledge/interview/bash/035-run-command-in-background.txt
bash/1f721f3a5161	bash	easy	bash, scripting	How can you create a temporary file safely in a script?	"By using the mktemp utility.\n\nGotcha: always quote variables in bash: ""$var"" prevents word splitting and glob expansion. Unquoted variables are the #1 source of bash bugs.\n\nRemember: bash is powerful but fragile. Use shellcheck (shellcheck.net) to catch common errors. It finds bugs that even experienced developers miss."	projects/knowledge/interview/bash/032-mktemp-command.txt
bash/2184ec7e2d89	bash	medium	bash, control-flow, scripting, text-processing	In shell scripting, how to check if a given argument is a number?	"```\nregex='^[0-9]+$'\nif [[ ${var//*.} =~ $regex ]]; then\n...\n```\n\nGotcha: always quote variables in bash: ""$var"" prevents word splitting and glob expansion. Unquoted variables are the #1 source of bash bugs.\n\nRemember: bash is powerful but fragile. Use shellcheck (shellcheck.net) to catch common errors. It finds bugs that even experienced developers miss."	projects/knowledge/interview/bash/013-in-shell-scripting-how-to-check-if-a-given-argumen.txt
bash/2765f29a89c9	bash	easy	bash, scripting	What does the $? variable store?	The exit status of the last executed command.\n\nRemember: $? = exit status of last command. 0 = success, non-zero = failure. Convention: 1 = general error, 2 = misuse, 126 = not executable, 127 = not found.	projects/knowledge/interview/bash/028-exit-status-variable.txt
bash/290c33ef4d9e	bash	medium	bash, variables	How to define a variable with the value of the current date?	`DATE=$(date)` — uses command substitution to run the `date` command and store its output (e.g., 'Tue Mar 18 14:00:00 UTC 2026') in the variable DATE. You can also use backtick syntax: DATE=`date`.\n\nRemember: for complex text processing, consider Python over bash. Bash excels at file operations and command orchestration; Python excels at data manipulation and error handling.	projects/knowledge/interview/bash/006-how-to-define-a-variable-with-the-value-of-the-cur.txt
bash/293035204c61	bash	medium	bash, control-flow, variables	How to compare variables length?	"```\nif [ ${#1} -ne ${#2} ]; then\n    ...\n```\n\nGotcha: always quote variables in bash: ""$var"" prevents word splitting and glob expansion. Unquoted variables are the #1 source of bash bugs.\n\nRemember: bash is powerful but fragile. Use shellcheck (shellcheck.net) to catch common errors. It finds bugs that even experienced developers miss."	projects/knowledge/interview/bash/012-how-to-compare-variables-length.txt
bash/2d1149a24bc1	bash	medium	bash, variables	"How to define a variable with the value ""Hello World""?"	"`HW=""Hello World`\n\nGotcha: always quote variables in bash: ""$var"" prevents word splitting and glob expansion. Unquoted variables are the #1 source of bash bugs.\n\nRemember: bash is powerful but fragile. Use shellcheck (shellcheck.net) to catch common errors. It finds bugs that even experienced developers miss."	projects/knowledge/interview/bash/005-how-to-define-a-variable-with-the-value-hello-worl.txt
bash/2d8b04d44591	bash	medium	bash, scripting, subshell	What is the difference between running a script with ./script.sh vs source script.sh?	./script.sh executes the script in a new subshell (changes don't affect the caller's environment), whereas source script.sh executes it in the current shell (so any exported variables or directory changes remain in your session).\n\nRemember: source script.sh (or . script.sh) runs in the current shell — variables and functions persist after execution. ./script.sh runs in a subshell — changes are lost.\n\nGotcha: sourcing a script that calls 'exit' will close your current terminal! Use 'return' in sourced scripts instead of 'exit.'	projects/knowledge/interview/bash/029-script-vs-source-execution.txt
bash/2db61122c8cd	bash	easy	bash, commands	How do you run a command in the background?	By appending an & to the end of the command.\n\nGotcha: bash scripts should start with set -euo pipefail for strict error handling. Without it, errors silently continue, producing wrong results.	projects/knowledge/interview/bash/040-background-command.txt
bash/2e03d0b810d9	bash	medium	bash, best-practices, scripting	How do you make maintainable Bash scripts?	Error handling (set -euo pipefail), small functions, validation, logging, and clear separation between config and logic. If a script grows too large, I rewrite it in Python.\n\nGotcha: set -e exceptions — commands in if/&&/|| do NOT trigger exit. Combine with set -o pipefail.\n\nExample: set -euo pipefail = recommended strict mode (error, undefined vars, pipe failures).\n\nRemember: for complex text processing, consider Python over bash. Bash excels at file operations and command orchestration; Python excels at data manipulation and error handling.	projects/knowledge/interview/bash/024-how-do-you-make-maintainable-bash-scripts.txt
bash/2e3f5fede050	bash	medium	bash, awk, scripting	How do you represent a single quote in an awk statement?	By using the octal code \047.\n\nExample: awk '{print $1, $3}' file.txt prints columns 1 and 3. awk -F: '{print $1}' /etc/passwd prints usernames.	projects/knowledge/interview/bash/030-awk-single-quote.txt
bash/2e4387301e96	bash	medium	bash, control-flow, scripting, text-processing	True or False? When a certain command/line fails in a shell script, the shell script, by default, will exit and stop running	Depends on the language and settings used.\nIf the script is a bash script then this statement is true. When a script written in Bash fails to run a certain command it will keep running and will execute all other commands mentioned after the command which failed.\n\nMost of the time we might actually want the opposite to happen. In order to make Bash exist when a specific command fails, use 'set -e' in your script.\n\nRemember: for complex text processing, consider Python over bash. Bash excels at file operations and command orchestration; Python excels at data manipulation and error handling.	projects/knowledge/interview/bash/002-true-or-false-when-a-certain-commandline-fails-in-.txt
bash/318ece2ca536	bash	medium	bash, networking, scripting, text-processing	"Write a script to print ""yay"" unless an argument was passed and then print that argument"	"```\necho ""${1:-yay}""\n```\n\nExample: sed -i 's/old/new/g' file.txt replaces all occurrences in-place. -i flag edits the file directly (use -i.bak for backup)."	projects/knowledge/interview/bash/008-write-a-script-to-print-yay-unless-an-argument-was.txt
bash/3a9d1681fc71	bash	medium	bash, scripting	What is the purpose of the : command in Bash?	It is a null command that does nothing but returns success (0).\n\nGotcha: bash scripts should start with set -euo pipefail for strict error handling. Without it, errors silently continue, producing wrong results.	projects/knowledge/interview/bash/026-colon-command-purpose.txt
bash/411bc213ca26	bash	medium	bash, control-flow, logging, scheduling	What does this line in shell scripts means?: #!/bin/bash	`#!/bin/bash` is She-bang\n\n/bin/bash is the most common shell used as default shell for user login of the linux system. The shell’s name is an acronym for Bourne-again shell. Bash can execute the vast majority of scripts and thus is widely used because it has more features, is well developed and better syntax.\n\nRemember: #!/usr/bin/env bash is more portable than #!/bin/bash. It finds bash in PATH, handling systems where bash is in /usr/local/bin.	projects/knowledge/interview/bash/001-what-does-this-line-in-shell-scripts-means-binbash.txt
bash/429fc948b634	bash	medium	bash, scripting	Running the following bash script, we don't get 2 as a result, why?	"Should be `x=2`\n\nGotcha: always quote variables in bash: ""$var"" prevents word splitting and glob expansion. Unquoted variables are the #1 source of bash bugs.\n\nRemember: bash is powerful but fragile. Use shellcheck (shellcheck.net) to catch common errors. It finds bugs that even experienced developers miss."	projects/knowledge/interview/bash/017-running-the-following-bash-script-we-dont-get-2-as.txt
bash/484fec58d6c4	bash	medium	bash	How to extract everything after the last dot in a string?	`${var##*.}` — this parameter expansion removes everything up to and including the last dot, leaving only the final extension. For example, if var='archive.tar.gz', then ${var##*.} yields 'gz'.\n\nGotcha: bash scripts should start with set -euo pipefail for strict error handling. Without it, errors silently continue, producing wrong results.	projects/knowledge/interview/bash/018-how-to-extract-everything-after-the-last-dot-in-a-.txt
bash/4b1ed67a66cd	bash	medium	bash, scripting, safety	What does set -u or set -o nounset do?	It causes the script to exit if an unset variable is referenced.\n\nGotcha: bash scripts should start with set -euo pipefail for strict error handling. Without it, errors silently continue, producing wrong results.	projects/knowledge/interview/bash/031-set-u-nounset.txt
bash/4b68111a8205	bash	medium	bash, control-flow, scripting, user-management	How do you get input from the user in shell scripts?	Using the keyword `read` so for example `read x` will wait for user input and will store it in the variable x.\n\nGotcha: bash scripts should start with set -euo pipefail for strict error handling. Without it, errors silently continue, producing wrong results.	projects/knowledge/interview/bash/011-how-do-you-get-input-from-the-user-in-shell-script.txt
bash/578f4ee2fe56	bash	medium	bash, control-flow	How to check if a given number has 4 as a factor?	"`if [ $(($1 % 4)) -eq 0 ]; then`\n\nGotcha: always quote variables in bash: ""$var"" prevents word splitting and glob expansion. Unquoted variables are the #1 source of bash bugs.\n\nRemember: bash is powerful but fragile. Use shellcheck (shellcheck.net) to catch common errors. It finds bugs that even experienced developers miss."	projects/knowledge/interview/bash/015-how-to-check-if-a-given-number-has-4-as-a-factor.txt
bash/5b72aa690921	bash	easy	bash, scripting	How do you perform arithmetic operations in Bash?	"Using the $((...)) syntax or the expr command.\n\nGotcha: always quote variables in bash: ""$var"" prevents word splitting and glob expansion. Unquoted variables are the #1 source of bash bugs.\n\nRemember: bash is powerful but fragile. Use shellcheck (shellcheck.net) to catch common errors. It finds bugs that even experienced developers miss."	projects/knowledge/interview/bash/036-arithmetic-operations.txt
bash/60e47d08bb94	bash	medium	bash, scripting	What does read -r do?	"Reads input without allowing backslashes to escape characters.\n\nGotcha: always quote variables in bash: ""$var"" prevents word splitting and glob expansion. Unquoted variables are the #1 source of bash bugs.\n\nRemember: bash is powerful but fragile. Use shellcheck (shellcheck.net) to catch common errors. It finds bugs that even experienced developers miss."	projects/knowledge/interview/bash/035-read-r-flag.txt
bash/633ce8014de8	bash	easy	bash, scripting, functions	How do you define a local variable within a Bash function?	By using the local keyword.\n\nRemember: variables are global by default in bash. Use 'local' keyword inside functions to limit scope. Missing 'local' = accidental side effects.	projects/knowledge/interview/bash/034-local-keyword.txt
bash/667186df372f	bash	easy	bash, scripting, arguments	How do you get the value of the first argument in a Bash script?	Use $1 (similarly, $2 for second, etc., and $@ for all arguments).\n\nGotcha: bash scripts should start with set -euo pipefail for strict error handling. Without it, errors silently continue, producing wrong results.	projects/knowledge/interview/bash/030-get-first-argument.txt
bash/6dac41af047b	bash	medium	bash, scripting	How do you make Bash scripts safe?	"Defense in depth:\n\n**Strict mode**:\n```bash\nset -euo pipefail\n```\n* `-e`: Exit on error\n* `-u`: Error on undefined variables\n* `-o pipefail`: Pipe fails if any command fails\n\n**Traps for cleanup**:\n```bash\ntrap 'rm -f ""$tmpfile""' EXIT\n```\n\n**Explicit paths**:\n```bash\nPATH=/usr/local/bin:/usr/bin:/bin\n```\n\n**Validate inputs**:\n```bash\n[[ -z ""${1:-}"" ]] && { echo ""Usage: $0 <arg>""; exit 1; }\n```\n\n**Logging**:\n```bash\nexec > >(tee -a ""$logfile"") 2>&1\n```\n\n**Parameter expansion safety**:\n```bash\nrm -rf ""${dir:?dir not set}""/*\n```\n\nThe most dangerous script is the one run with confidence and no backup.\n\nRemember: for complex text processing, consider Python over bash. Bash excels at file operations and command orchestration; Python excels at data manipulation and error handling."	projects/knowledge/interview/bash/025-how-do-you-make-scripts-safe.txt
bash/7c680c877686	bash	medium	bash, networking, commands	How do you check the settings of a Network Interface Card (NIC)?	ethtool. It queries and controls NIC settings: `ethtool eth0` shows speed/duplex/link, `ethtool -i eth0` shows driver info, `ethtool -S eth0` shows NIC-level counters.\n\nGotcha: bash scripts should start with set -euo pipefail for strict error handling. Without it, errors silently continue, producing wrong results.	projects/knowledge/interview/bash/042-ethtool-command.txt
bash/7d8d077946e0	bash	easy	bash, fundamentals	What is Bash and why is it the default shell on most Linux systems?	Bash (Bourne Again SHell) is a Unix shell and command language used as the default shell on many Linux systems; it allows running commands and scripting to automate tasks.\n\nGotcha: bash scripts should start with set -euo pipefail for strict error handling. Without it, errors silently continue, producing wrong results.	projects/knowledge/interview/bash/026-what-is-bash.txt
bash/8ae2083aef2a	bash	medium	bash	How to perform arithmetic operations on numbers?	One way: `$(( 1 + 2 ))`\nAnother way: `expr 1 + 2`\n\nGotcha: bash scripts should start with set -euo pipefail for strict error handling. Without it, errors silently continue, producing wrong results.	projects/knowledge/interview/bash/014-how-to-perform-arithmetic-operations-on-numbers.txt
bash/8b41f409dd0e	bash	easy	bash, export, environment	What does the export command do in Bash?	It marks a shell variable to be passed to child processes as an environment variable (e.g., export VAR=value).\n\nGotcha: bash scripts should start with set -euo pipefail for strict error handling. Without it, errors silently continue, producing wrong results.	projects/knowledge/interview/bash/036-what-does-export-do.txt
bash/8d4fcc8854c1	bash	medium	bash, scripting	What would be the output of the following script?	Michelangelo — the script outputs this name because the associative array or indexed variable lookup resolves to this value based on the index/key used in the print or echo statement.\n\nRemember: for complex text processing, consider Python over bash. Bash excels at file operations and command orchestration; Python excels at data manipulation and error handling.	projects/knowledge/interview/bash/009-what-would-be-the-output-of-the-following-script-u.txt
bash/8ddfbe5752d9	bash	easy	bash, scripting, automation	Tell me about your scripting background.	Bash is my strongest language — I've written everything from automation frameworks to custom DSLs for managing large server fleets. I focus on clean logic, predictable behavior, safe defaults, and portability. I've also used Python and Perl for tasks where stronger data structures or libraries were needed.\n\nRemember: for complex text processing, consider Python over bash. Bash excels at file operations and command orchestration; Python excels at data manipulation and error handling.	projects/knowledge/interview/bash/023-tell-me-about-your-scripting-background.txt
bash/8fe9b80cc303	bash	easy	bash, arrays, scripting, text-processing	What is difference between $@ and $*?	"`$@` is an array of all the arguments passed to the script\n`$*` is a single string of all the arguments passed to the script\n\nExample: with args 'hello world' and 'foo': ""$@"" = two args ('hello world', 'foo'). ""$*"" = one arg ('hello world foo'). Always use ""$@"" to preserve argument boundaries.\n\nRemember: for complex text processing, consider Python over bash. Bash excels at file operations and command orchestration; Python excels at data manipulation and error handling."	projects/knowledge/interview/bash/010-what-is-difference-between-and.txt
bash/909969329f75	bash	medium	bash, ansible, kernel, logging	Today we have tools and technologies like Ansible, Puppet, Chef, ... Why would someone still use shell scripting?	"* Speed\n  * Flexibility\n  * The module we need doesn't exist (perhaps a weak point because most CM technologies allow to use what is known as ""shell"" module)\n  * We are delivering the scripts to customers who don't have access to the public network and don't necessarily have Ansible installed on their systems.\n\nRemember: for complex text processing, consider Python over bash. Bash excels at file operations and command orchestration; Python excels at data manipulation and error handling."	projects/knowledge/interview/bash/004-today-we-have-tools-and-technologies-like-ansible-.txt
bash/9148ab2a3610	bash	medium	bash, operators, control-flow	What do && and || do in Bash command execution?	cmd1 && cmd2 runs cmd2 only if cmd1 succeeds (exit status 0). cmd1 || cmd2 runs cmd2 only if cmd1 fails (non-zero exit status).\n\nRemember: cut -d',' -f1 extracts the first comma-separated field. -d sets delimiter, -f selects fields. For complex parsing, prefer awk.	projects/knowledge/interview/bash/034-and-or-operators.txt
bash/9c4b8778fe7f	bash	medium	bash, networking, piping, processes	What does the following code do and when would you use it?	It is called 'process substitution'. It provides a way to pass the output of a command to another command when using a pipe `|` is not possible. It can be used when a command does not support `STDIN` or you need the output of multiple commands.\nhttps://superuser.com/a/1060002/167769\n\nRemember: for complex text processing, consider Python over bash. Bash excels at file operations and command orchestration; Python excels at data manipulation and error handling.	projects/knowledge/interview/bash/022-what-does-the-following-code-do-and-when-would-you.txt
bash/ac02ab67e805	bash	medium	bash, scripting, set, errexit	What does set -e do in a Bash script?	It enables errexit mode – the script will exit immediately if any command returns a non-zero (error) status.\n\nGotcha: set -e has exceptions — commands in if/&&/|| do NOT trigger exit. Combine with set -o pipefail for safer scripts.\n\nExample: set -euo pipefail is the recommended strict mode preamble (exit on error, undefined vars, pipe failures).\n\nRemember: set -euo pipefail is the 'strict mode' trinity: -e (exit on error), -u (undefined vars are errors), -o pipefail (pipe failures propagate).\n\nGotcha: set -e does NOT catch errors in if conditions, || chains, or command substitutions. Use explicit error handling for critical sections.	projects/knowledge/interview/bash/038-what-does-set-e-do.txt
bash/b8cf677ddf64	bash	easy	bash, scripting, arguments	How do you get the number of arguments passed to a Bash script?	$# expands to the count of positional parameters (arguments) passed to the script.\n\nExample: sed -i 's/old/new/g' file.txt replaces all occurrences in-place. -i flag edits the file directly (use -i.bak for backup).	projects/knowledge/interview/bash/031-get-number-of-arguments.txt
bash/bef643a5ab66	bash	medium	bash, variables, environment	What's the difference between an environment variable and a shell variable?	A shell variable is local to the current shell session, whereas an environment variable is exported and available to child processes. (You use export to turn a shell variable into an environment variable.)\n\nRemember: for complex text processing, consider Python over bash. Bash excels at file operations and command orchestration; Python excels at data manipulation and error handling.	projects/knowledge/interview/bash/037-environment-vs-shell-variable.txt
bash/c8af2cff62e1	bash	medium	bash, scripting	When do you stop using Bash?	Bash is glue, not an application framework. Stop when:\n\n**State grows**: Managing complex data structures, nested objects → use Python/Go.\n\n**Complexity grows**: More than ~200 lines, multiple files → real language.\n\n**Error handling matters**: Bash error handling is clunky. If reliability is critical, use something better.\n\n**Portability needed**: Bash versions differ. POSIX sh is safer but limited.\n\n**Testing required**: Bash testing is possible but painful. Real languages have real test frameworks.\n\n**Good use cases for Bash**:\n* Glue scripts (calling other tools)\n* Simple automation\n* One-off tasks\n* Boot scripts, init\n\nBash should connect things, not BE the thing.	projects/knowledge/interview/bash/024-when-do-you-stop-using-bash.txt
bash/c965d86e6640	bash	medium	bash, processes, commands	How do you change the priority of a running process?	renice. It adjusts the nice value of a running process: `renice -n 10 -p <PID>` lowers priority, `renice -n -5 -p <PID>` raises it (requires root for negative values).\n\nGotcha: bash scripts should start with set -euo pipefail for strict error handling. Without it, errors silently continue, producing wrong results.	projects/knowledge/interview/bash/044-renice-command.txt
bash/d0831e44b98e	bash	medium	bash, scripting	What separates good Bash from bad?	"The basics that most scripts get wrong:\n\n**Quoting**: Always quote variables. `""$var""` not `$var`. Unquoted variables break on spaces and glob.\n\n**Error handling**: Check return codes. Use `set -e` or explicit checks. Don't assume commands succeed.\n\n**Idempotence**: Running twice should be safe. Check before acting.\n\n**Readability**: Clear variable names, comments for non-obvious logic, consistent formatting.\n\n**Bad script**:\n```bash\nrm -rf $dir/*\n```\n\n**Good script**:\n```bash\nset -euo pipefail\nif [[ -d ""$dir"" ]]; then\n    rm -rf ""${dir:?}""/*\nfi\n```\n\nIf you can't read your script in 6 months, it's bad Bash.\n\nRemember: for complex text processing, consider Python over bash. Bash excels at file operations and command orchestration; Python excels at data manipulation and error handling."	projects/knowledge/interview/bash/023-what-separates-good-bash-from-bad.txt
bash/d70e9634c742	bash	medium	bash, scripting	What is the primary advantage of the [[ keyword over [?	It supports regular expressions and is less prone to word-splitting errors.\n\nRemember: file tests: -f (regular file), -d (directory), -e (exists), -r (readable), -w (writable), -x (executable), -s (non-empty). String tests: -z (empty), -n (non-empty).	projects/knowledge/interview/bash/029-double-bracket-advantage.txt
bash/d9103eec40ce	bash	medium	bash	How to extract everything before the last dot in a string?	${var%.*} — uses bash parameter expansion. The `%` operator removes the shortest match of `.*` from the end. For greedy (last dot): `${var%%.*}`.\n\nGotcha: bash scripts should start with set -euo pipefail for strict error handling. Without it, errors silently continue, producing wrong results.	projects/knowledge/interview/bash/019-how-to-extract-everything-before-the-last-dot-in-a.txt
bash/db21df164e98	bash	easy	bash, scripting, exit-status	How do you check the exit status of the last command in Bash?	$? contains the exit status (0 means success, non-zero indicates an error).\n\nGotcha: bash scripts should start with set -euo pipefail for strict error handling. Without it, errors silently continue, producing wrong results.	projects/knowledge/interview/bash/032-check-exit-status.txt
bash/dbb98d1d632d	bash	easy	bash, scripting, arithmetic	How do you do arithmetic in Bash?	Using arithmetic expansion or the expr command. For example, result=$((2+2)) sets result to 4.\n\nGotcha: bash scripts should start with set -euo pipefail for strict error handling. Without it, errors silently continue, producing wrong results.	projects/knowledge/interview/bash/040-arithmetic-in-bash.txt
bash/df2197abbdec	bash	medium	bash, scripting, text-processing	How to print the first argument passed to a script?	`echo $1` — `$1` is the first positional parameter. `$0` is the script name, `$#` is the argument count, and `$@` expands to all arguments.\n\nExample: sed -i 's/old/new/g' file.txt replaces all occurrences in-place. -i flag edits the file directly (use -i.bak for backup).	projects/knowledge/interview/bash/007-how-to-print-the-first-argument-passed-to-a-script.txt
bash/e5d0337074aa	bash	medium	bash, commands, redirection	What does 2>&1 signify?	Redirects standard error (stderr) to standard output (stdout).\n\nRemember: > = stdout to file, 2> = stderr to file, &> = both to file, 2>&1 = stderr to where stdout goes. Order matters!\n\nExample: command > output.log 2>&1 captures both stdout and stderr. command 2>&1 > file sends stderr to terminal, stdout to file (probably not what you want).	projects/knowledge/interview/bash/039-stderr-to-stdout.txt
bash/e72834841ed8	bash	easy	bash, scripting, command-substitution	How can you capture the output of a command into a variable in Bash?	Use command substitution: either backticks `command` or $(command) (e.g., RESULT=`uname -r` or RESULT=$(uname -r)).\n\nExample: files=$(ls *.txt) captures output. $() nests cleanly: $(echo $(date)). Preferred over backticks.\n\nGotcha: bash scripts should start with set -euo pipefail for strict error handling. Without it, errors silently continue, producing wrong results.	projects/knowledge/interview/bash/039-capture-command-output.txt
bash/e7f5eb102a2e	bash	easy	bash, redirection	What is the difference between > and >> in Bash redirection?	> redirects output to a file (overwriting it), whereas >> appends the output to the end of the file (without overwriting existing content).\n\nRemember: > = stdout to file, 2> = stderr to file, &> = both to file, 2>&1 = stderr to where stdout goes. Order matters!\n\nExample: command > output.log 2>&1 captures both stdout and stderr. command 2>&1 > file sends stderr to terminal, stdout to file (probably not what you want).	projects/knowledge/interview/bash/033-redirect-vs-append.txt
bash/ea5e99123fdb	bash	medium	bash, scripting, signals	What is the purpose of the trap command?	To execute a command or function when the script receives a signal.\n\nExample: trap 'rm -f /tmp/lockfile' EXIT ensures cleanup on exit, even on error/Ctrl+C.\n\nExample: trap 'rm -f /tmp/lockfile' EXIT ensures cleanup runs even if the script fails. Trap signals: EXIT, ERR, INT, TERM.	projects/knowledge/interview/bash/033-trap-command.txt
bash/ecdcc5185625	bash	easy	bash, commands	What does the | (pipe) operator do?	Passes the output of one command as input to another command.\n\nRemember: pipe (|) connects stdout of left command to stdin of right command. Data flows left to right. Like UNIX Lego blocks.\n\nExample: ps aux | grep nginx | awk '{print $2}' | xargs kill — find nginx PIDs and kill them. Each | is a handoff.	projects/knowledge/interview/bash/037-pipe-operator.txt
bash/fcd31bd9c94b	bash	medium	bash, control-flow, scripting, text-processing	What do you tend to include in every script you write?	"Few example:\n\n  * Comments on how to run it and/or what it does\n  * If a shell script, adding ""set -e"" since I want the script to exit if a certain command failed\n\nYou can have an entirely different answer. It's based only on your experience and preferences.\n\nRemember: for complex text processing, consider Python over bash. Bash excels at file operations and command orchestration; Python excels at data manipulation and error handling."	projects/knowledge/interview/bash/003-what-do-you-tend-to-include-in-every-script-you-wr.txt
bash/z1a9b3c5d7e2	bash	easy	bash,quoting,single-quotes	What is the output of echo '$HOME' in bash?	"The literal string $HOME. Single quotes suppress all expansion.\n\nGotcha: always quote variables in bash: ""$var"" prevents word splitting and glob expansion. Unquoted variables are the #1 source of bash bugs.\n\nRemember: bash is powerful but fragile. Use shellcheck (shellcheck.net) to catch common errors. It finds bugs that even experienced developers miss."	zines/bite.size.bash.cleaned.notes
bash/z2b0c4d6e8f3	bash	medium	bash,quoting,double-quotes,expansion	What expansions occur inside double quotes in bash?	"Variable expansion ($VAR, ${VAR}) and command substitution ($(...)) occur. Globbing and word splitting do not.\n\nExample: files=$(ls *.txt) captures output. $() nests cleanly: $(echo $(date)). Preferred over backticks.\n\nRemember: 'single quotes' = literal (no expansion). ""double quotes"" = expands $variables and $(commands). Use double quotes almost always to prevent word splitting."	zines/bite.size.bash.cleaned.notes
bash/z3c1d5e7f9a4	bash	medium	bash,set,pipefail,safety	What does set -o pipefail do and why is it needed beyond set -e?	Without pipefail, a pipeline's exit status is the last command's status. With pipefail, the pipeline fails if ANY command in the pipe fails. set -e alone misses mid-pipe failures.\n\nGotcha: set -e exceptions — commands in if/&&/|| do NOT trigger exit. Combine with set -o pipefail.\n\nExample: set -euo pipefail = recommended strict mode (error, undefined vars, pipe failures).\n\nRemember: set -euo pipefail is the 'strict mode' trinity: -e (exit on error), -u (undefined vars are errors), -o pipefail (pipe failures propagate).\n\nGotcha: set -e does NOT catch errors in if conditions, || chains, or command substitutions. Use explicit error handling for critical sections.	zines/bite.size.bash.cleaned.notes
bash/z4d2e6f8a0b5	bash	easy	bash,variables,assignment	Why does x = 2 fail but x=2 works in bash?	Bash interprets x = 2 as running a command called x with arguments = and 2. Variable assignment requires no spaces around the equals sign.\n\nGotcha: bash scripts should start with set -euo pipefail for strict error handling. Without it, errors silently continue, producing wrong results.	zines/bite.size.bash.cleaned.notes
bash/z5e3f7a9b1c6	bash	medium	bash,test,conditional	Why does bash if test the exit status of a command rather than a boolean expression?	Because bash is a shell language first. if runs a command and branches on its exit code (0 = true, non-zero = false). [ and [[ are commands/keywords that evaluate expressions and return exit codes.\n\nRemember: [ is a command (test), [[ is a bash keyword (more features). Use [[ for pattern matching, regex, and safer quoting.	zines/bite.size.bash.cleaned.notes
bash/z6f4a8b0c2d7	bash	medium	bash,unquoted,word-splitting,globbing	What two dangers arise from leaving a variable unquoted in bash?	Word splitting (spaces in the value become separate arguments) and filename globbing (wildcards like * expand to matching files). Both can cause unexpected behavior or security issues.\n\nGotcha: bash scripts should start with set -euo pipefail for strict error handling. Without it, errors silently continue, producing wrong results.	zines/bite.size.bash.cleaned.notes
bash/z7a5b9c1d3e8	bash	hard	bash,set,errexit,gotchas	Name a situation where set -e does NOT cause the script to exit on error.	Commands in the condition of an if statement, commands in a pipeline (without pipefail), commands after && or ||, and commands inside $(...) subshells do not trigger errexit. This is why set -e should be used carefully, not superstitiously.\n\nRemember: set -euo pipefail is the 'strict mode' trinity: -e (exit on error), -u (undefined vars are errors), -o pipefail (pipe failures propagate).\n\nGotcha: set -e does NOT catch errors in if conditions, || chains, or command substitutions. Use explicit error handling for critical sections.	zines/bite.size.bash.cleaned.notes
bash/z8b6c0d2e4f9	bash	easy	bash,command-substitution,backticks	Why prefer $(...) over backticks for command substitution?	$(...) nests cleanly, is easier to read, and avoids confusing escaping rules. Backticks are legacy syntax.\n\nExample: files=$(ls *.txt) captures output. $() nests cleanly: $(echo $(date)). Preferred over backticks.\n\nGotcha: bash scripts should start with set -euo pipefail for strict error handling. Without it, errors silently continue, producing wrong results.	zines/bite.size.bash.cleaned.notes
bash/4bec1eb2d377	bash	medium	miscellaneous, arrays, control-flow, logging	What are the advantages of using RAID (Redundant Array of Independent Disks) in a server environment?	RAID is a technology that combines multiple physical disk drives into a single logical unit for the purpose of data redundancy, improved performance, or both. The advantages of using RAID in a server environment include: **Data Redundancy:* • RAID provides fault tolerance by duplicating or parity-checking data across multiple drives. In the event of a drive failure, data can be reconstructed from the redundancy, ensuring data integrity and availability .\n\nExample: arr=(a b c); echo ${arr[0]} prints 'a'. ${arr[@]} expands all elements. ${#arr[@]} gives the count.	
bash/6fae9a2234f9	bash	medium	miscellaneous, arrays, control-flow, filesystem	Explain the concept of LUN (Logical Unit Number) in storage management.	A Logical Unit Number (LUN) is a unique identifier assigned to a logical unit, which is a representation of a subset of a storage subsystem. In storage management, a LUN is typically associated with storage area networks (SANs) and is used to define a logical volume or unit of storage presented to a server. **Key points about LUNs include:* •  • Identification: A LUN is identified by a number or address that allows a server to access a specific portion of storage within a storage array.	
bash/e863fa35d076	bash	medium	miscellaneous, arrays, backup, control-flow	Discuss the steps you would take to recover data from a failed storage device.	• Assess the Failure: Determine the nature of the storage failure (logical, physical, or both). • Isolate the Device: Isolate the failed storage device to prevent further damage or data loss. • Verify Backups: Confirm the availability and integrity of recent backups. • Use Data Recovery Tools: Explore data recovery tools that may be able to recover data from the failed storage device. • Engage Data Recovery Services: If necessary, consider engaging professional data recovery services for physical damage or complex issues.	

<!-- wiki:related:start -->
---

## Wiki Navigation

### Related Content

- [Advanced Bash for Ops](../../../../library/topics/advanced-bash/index.md) (Topic Pack, L1) — Bash / Shell Scripting
- Bash Exercises (Quest Ladder) *(CLI)* (Exercise Set, L0) — Bash / Shell Scripting
- [Cron & Job Scheduling](../../../../library/topics/cron-scheduling/index.md) (Topic Pack, L1) — Bash / Shell Scripting
- [Environment Variables](../../../../library/topics/environment-variables/index.md) (Topic Pack, L1) — Bash / Shell Scripting
- [Fleet Operations at Scale](../../../../library/topics/fleet-ops/index.md) (Topic Pack, L2) — Bash / Shell Scripting
- [LPIC / LFCS Exam Preparation](../../../../library/topics/lpic-lfcs/index.md) (Topic Pack, L2) — Bash / Shell Scripting
- [Linux Ops](../../../../library/topics/linux-ops/index.md) (Topic Pack, L0) — Bash / Shell Scripting
- [Linux Ops Drills](../../../../library/drills/linux_ops_drills.md) (Drill, L0) — Bash / Shell Scripting
- [Linux Text Processing](../../../../library/topics/linux-text-processing/index.md) (Topic Pack, L1) — Bash / Shell Scripting
- [Make & Build Systems](../../../../library/topics/make-and-build-systems/index.md) (Topic Pack, L1) — Bash / Shell Scripting

<!-- wiki:related:end -->
