Tags: bash, shell, scripting, linux, cli
Level: intermediate
TL;DR: Essential syntax, control structures, and command-line execution patterns for Bash scripting and daily terminal usage.
Bash scripts execute sequentially and require a valid shebang (#!/bin/bash) at the top.
Variables are assigned without spaces (VAR="value") and referenced with a dollar sign ($VAR).
Exit status ($?) indicates the success (0) or failure (>0) of the most recently executed command.
Pipes (|) chain commands by passing standard output from one as standard input to the next.
Output redirection uses > to overwrite and >> to append to a file.
Positional parameters ($1, $2) handle arguments passed to scripts or functions.
Command substitution ($(command)) captures the output of a command into a variable.
The test construct ([[ condition ]]) is preferred over [ for string and file evaluations.
Q: What is the difference between single and double quotes in Bash?R: Single quotes preserve the literal value of all characters. Double quotes allow for variable expansion and command substitution.
Q: How do you redirect both standard error and standard output to the same file?R: I use command > file.txt 2>&1 or the shorter syntax command &> file.txt.
Q: How do you handle numerical comparisons versus string comparisons?R: I use operators like -eq, -lt, and -gt for integers, and =, !=, <, > for strings.
Adding spaces around the assignment operator (e.g., VAR = "value" causes a command not found error).
Failing to wrap variable references in double quotes (e.g., "$VAR"), which breaks scripts if the variable contains spaces or is empty.
Using a trailing slash in rsync or copy commands incorrectly, which alters whether the directory itself or its contents are copied.
# Basic if statement
if [[ -f "/etc/hosts" ]]; then
echo "File exists."
else
echo "File not found."
fi
# For loop over files
for file in *.txt; do
echo "Processing $file"
done
# Function with arguments
greet() {
local name=$1
echo "Hello, $name!"
}
greet "World"