The [[ ]] extended test lets you check conditions in bash scripts easily. It helps decide what to do next based on facts.
Check if a file exists before reading it.
Compare two numbers to choose a path.
Test if a string is empty or not.
Verify if a directory is writable.
Decide actions based on user input.
Syntax
Bash Scripting
[[ condition ]]
# Example:if [[ $var -eq 5 ]]; then
echo "Equal to 5"
fi
Use [[ ]] inside if statements or loops to test conditions.
Supports many operators like -eq, -ne, <, >, string tests, and file tests.
Examples
Tests if variable num is greater than 10.
Bash Scripting
[[ $num -gt 10 ]]
Checks if the file /etc/passwd exists and is a regular file.
Bash Scripting
[[ -f /etc/passwd ]]
Tests if the string variable str equals "hello".
Bash Scripting
[[ $str == "hello" ]]
Checks if /tmp is a directory.
Bash Scripting
[[ -d /tmp ]]
Sample Program
This script asks for a number and tells if it is positive, zero, or negative using [[ ]] tests.
Bash Scripting
#!/bin/bash
read -p "Enter a number: " num
if [[ $num -gt 0 ]]; then
echo "Positive number"elif [[ $num -eq 0 ]]; then
echo "Zero"else
echo "Negative number"
fi
OutputSuccess
Important Notes
[[ ]] is safer and more powerful than [ ] in bash.
Inside [[ ]], you don't need to quote variables to prevent word splitting.
Use && and || inside [[ ]] for combining conditions.
Summary
[[ ]] tests conditions in bash scripts simply and clearly.
It supports numbers, strings, and file checks.
Use it to control script flow based on facts.
Practice
(1/5)
1. What does the [[ ]] construct do in a bash script?
easy
A. It tests conditions like comparing strings or numbers.
B. It defines a function in bash.
C. It creates a new variable.
D. It runs a command in the background.
Solution
Step 1: Understand the purpose of [[ ]]
The [[ ]] syntax is used in bash to test conditions such as string comparison, number comparison, and file checks.
Step 2: Compare with other options
Options B, C, and D describe other bash features unrelated to [[ ]].
Final Answer:
It tests conditions like comparing strings or numbers. -> Option A
Quick Check:
[[ ]] = condition test [OK]
Hint: Remember: [[ ]] is for testing conditions in bash [OK]
Common Mistakes:
Confusing [[ ]] with function definition syntax
Thinking [[ ]] creates variables
Assuming [[ ]] runs commands
2. Which of the following is the correct syntax to check if variable var equals "hello" using [[ ]]?
easy
A. [[ $var != "hello" ]]
B. [[ $var == "hello" ]]
C. [[ $var === "hello" ]]
D. [[ $var -eq "hello" ]]
Solution
Step 1: Identify correct string comparison operator in [[ ]]
In bash, inside [[ ]], the operator for string equality is ==. -eq is for numeric equality. === is invalid.