0
0
Bash Scriptingscripting~3 mins

Why [[ ]] extended test in Bash Scripting? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a simple syntax change can save you from frustrating script errors!

The Scenario

Imagine you have a list of files and you want to check if each file exists and is not empty before processing it. Doing this manually means typing multiple commands for each file, checking conditions one by one.

The Problem

Manually checking each file is slow and easy to forget important checks. You might miss empty files or accidentally process non-existent ones, causing errors or wasted time.

The Solution

The [[ ]] extended test in bash lets you write clear, concise conditions to check files and other things in one place. It reduces mistakes and speeds up your scripts.

Before vs After
Before
if [ -e file.txt ] && [ -s file.txt ]; then echo 'File is ready'; fi
After
if [[ -e file.txt && -s file.txt ]]; then echo 'File is ready'; fi
What It Enables

You can write safer, cleaner scripts that handle complex checks easily and avoid common errors.

Real Life Example

When backing up important documents, you can use [[ ]] to ensure only existing and non-empty files get copied, preventing backup failures.

Key Takeaways

Manual checks are slow and error-prone.

[[ ]] lets you combine tests cleanly.

This makes scripts safer and easier to read.