What is command substitution in bash?

Why Interviewers Ask This

This question targets practical, hands-on experience with Linux / Shell Scripting. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.

Answer

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.

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Linux / Shell Scripting answers easy to follow.