1. Test a file
[ ... ] is the test command; -f is true when config.txt is a regular file.
if [ -f "config.txt" ]; thenTyporithm · medium
Step 1 of 8 · intro card
Basics
if [ test ]; then ... fi runs a block when a test passes. [ -f file ] checks for a regular file, [ -d dir ] a directory, [ -z str ] an empty string. elif chains more conditions and else is the fallback; [[ ... ]] is bash's extended test.
An if statement runs a block based on a test. [ ... ] is the classic test command: -f "config.txt" is true when the file exists as a regular file, -d "src" when it is a directory, and -z is true for an empty string.
The ; then starts the block and fi (if spelled backwards) closes it. elif chains an additional condition tested only when earlier ones failed, and else is the catch-all that runs when nothing matched.
Bash also offers [[ ... ]], an extended test that supports && and || directly and pattern matching like [[ $x == a* ]], avoiding many quoting pitfalls of the older [ ... ] form.
[ ... ] is the test command; ; then and fi delimit the block.
-f tests a file, -d a directory, -z an empty string.
elif chains conditions; else is the fallback.
if [ -f "config.txt" ]; then
echo "found"
elif [ -d "src" ]; then
echo "dir"
else
echo "missing"
fiConnect each part of the code to the concept before you type.
[ ... ] is the test command; -f is true when config.txt is a regular file.
if [ -f "config.txt" ]; then; then begins the block that runs when the condition is true.
; thenelif chains another condition; -d is true when src is a directory.
elif [ -d "src" ]; thenelse runs when no preceding condition matched.
elsefi closes the if/elif/else block — if spelled backwards.
fiRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.