0
0
Bash Scriptingscripting~5 mins

[[ ]] extended test in Bash Scripting

Choose your learning style9 modes available
Introduction

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.