Intermediate LevelLinux Commands & SysAdmin
How do variables, if/else conditionals, loops, and exit codes work in Bash scripts?
❓ Interview Prompt: Explain Bash script syntax, shebang (#!/bin/bash), variables, positional parameters ($1, $2, $@), exit codes ($?), if statements, and loops.
Bash scripts automate repetitive operational tasks:
Key Syntax Rules:
•
Shebang: First line ('#!/bin/bash') specifying shell interpreter.
•
Positional Parameters: '$1', '$2' (arguments), '$#' (arg count), '$@' (all args).
•
Exit Codes: '$?' stores status of last command (0 = success, 1-255 = error).
•
Conditionals: 'if [ -f "/etc/file" ]; then ... fi'
Code Implementation Example
bash
#!/bin/bash
# Script checking if server process is running
PROCESS_NAME="nginx"
if pgrep "$PROCESS_NAME" > /dev/null; then
echo "$PROCESS_NAME is running."
exit 0
else
echo "ERROR: $PROCESS_NAME is stopped!" >&2
exit 1
fi💡Automated Bash process monitoring script with conditional exit codes.
🎯 Interview Key Takeaway
Structure Bash scripts with explicit shebangs, variable quotes, and meaningful exit codes (0 success, non-zero error).
#Bash Scripting#Conditionals#Exit Codes#Intermediate
Back to all Linux Commands & SysAdmin Questions→