QA
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→

More Linux Commands & SysAdmin Interview Questions

Beginner LevelLinux Commands & SysAdmin

How do Linux File Permissions (chmod, chown, chgrp) work in Octal and Symbolic notation?

Beginner LevelLinux Commands & SysAdmin

What is the Linux Filesystem Hierarchy Standard (/bin, /etc, /var, /usr, /opt, /tmp)?

Beginner LevelLinux Commands & SysAdmin

What are File Descriptors (0=stdin, 1=stdout, 2=stderr) and Redirection (>, >>, 2>&1)?