🐧 Linux / Shell Scripting
Intermediate
How do you write if/for/while/case statements in bash?
Answer
Bash control structures: if: if [ "$var" = "value" ]; then echo yes; elif ...; else echo no; fi. Use [[ ]] (double brackets) for more features like =~ regex matching. for: for i in 1 2 3; do echo $i; done or C-style: for ((i=0; i<10; i++)); do ...; done. while: while read line; do ...; done < file reads a file line by line. case: case "$arg" in start) start_service;; stop) stop_service;; *) echo "unknown";; esac. Key test operators: -f (file exists), -d (directory), -z (string empty), -n (string not empty), -eq/-ne/-lt/-gt for numeric comparisons.