0
0
Bash Scriptingscripting~5 mins

test command and [ ] syntax in Bash Scripting

Choose your learning style9 modes available
Introduction
The test command and [ ] syntax help check conditions in scripts to decide what to do next.
Check if a file exists before reading it.
Compare two numbers to see which is bigger.
See if a variable is empty or not.
Decide what to do based on user input.
Verify if a directory is present before creating files.
Syntax
Bash Scripting
test CONDITION
[ CONDITION ]
Both test and [ ] do the same thing: check a condition.
Make sure to put spaces around [ and ] when using [ ].
Examples
Check if a file named filename.txt exists.
Bash Scripting
test -f filename.txt
if [ -f filename.txt ]; then echo "File exists"; fi
Check if variable var equals 'hello'.
Bash Scripting
if [ "$var" = "hello" ]; then echo "Greeting found"; fi
Check if number num is greater than 10.
Bash Scripting
if test $num -gt 10; then echo "Number $num is greater than 10"; fi
Sample Program
This script checks if a file named myfile.txt exists and prints a message. Then it checks if the number 5 is less than 10 and prints the result.
Bash Scripting
#!/bin/bash

filename="myfile.txt"

if [ -e "$filename" ]; then
  echo "File '$filename' exists."
else
  echo "File '$filename' does not exist."
fi

num=5
if test $num -lt 10; then
  echo "Number $num is less than 10."
else
  echo "Number $num is 10 or more."
fi
OutputSuccess
Important Notes
Always put spaces after [ and before ] when using [ ] syntax.
Use quotes around variables to avoid errors if they are empty or have spaces.
test and [ ] are interchangeable, but [ ] is more common in scripts.
Summary
test and [ ] check conditions in bash scripts.
Use them to make decisions like if-else.
Remember spaces and quotes to avoid mistakes.