• Skip to main content
  • Skip to primary sidebar
  • Home
  • WordPress
  • web Hosting
  • linux
  • mysql
  • nginx
  • apache2
  • devops

Raju Ginni

wordpress tutorials seo hosting etc

You are here: Home / Linux sysadmin tutorials linux system administrator / Bash Brackets ([], (), {}, $( ), $(( ))) – Types, Uses & Examples

Bash Brackets ([], (), {}, $( ), $(( ))) – Types, Uses & Examples

In Bash scripting, different types of brackets are used for various operations, such as condition checking, command substitution, array handling, and arithmetic operations. Below is a detailed guide with examples.


Table of Contents

Toggle
  • 📌 Key Highlights of  Bash Brackets
  • 📌 1. Square Brackets [] (Test Conditions)
    • ✅ Example 1: Check if a File Exists
    • ✅ Example 2: String Comparison
    • ✅ Example 3: Integer Comparisons
  • 📌 2. Double Square Brackets [[ ]] (Advanced Test Conditions)
    • ✅ Example 4: String Matching with Wildcards
    • ✅ Example 5: Regex Matching
  • 📌 3. Parentheses () (Command Grouping & Subshells)
    • ✅ Example 6: Grouping Commands
    • ✅ Example 7: Background Process
  • 📌 4. Double Parentheses $(( )) (Arithmetic Operations)
    • ✅ Example 8: Basic Arithmetic
    • ✅ Example 9: Increment & Decrement
  • 📌 5. Curly Braces {} (Variable Expansion & Loops)
    • ✅ Example 10: Variable Expansion
    • ✅ Example 11: Looping with Brace Expansion
    • ✅ Example 12: Multiple Command Execution
  • 📌 6. Command Substitution $( )
    • ✅ Example 13: Store Command Output
    • ✅ Example 14: Using Command Substitution in a Loop
  • 📌 7. Dollar Sign & Curly Brackets ${} (Variable Manipulation)
    • ✅ Example 15: Get String Length
    • ✅ Example 16: Remove Part of a String
  • 🔥 Bash Brackets Interview Questions & Answers
    • 📌 Basic Questions
    • 1️⃣ What is the difference between [ ] and [[ ]] in Bash?
    • 2️⃣ What is the use of {} in Bash?
    • 3️⃣ What is the difference between ( ) and { } in Bash?
    • 📌 Intermediate Questions
    • 4️⃣ How do $(( )) and $( ) differ in Bash?
    • 5️⃣ What happens if you don’t use curly braces ${} for variables in Bash?
    • 6️⃣ How do you use [[ ]] for pattern matching?
    • 📌 Advanced Questions
    • 7️⃣ How do you use [[ ]] with regex?
    • 8️⃣ How do you compare numbers correctly in Bash?
    • 9️⃣ How do you use brace expansion {} in Bash loops?
    • 🔟 How do you use ${} for string operations?
  • 🔥 Bonus: Quick Comparison Table
  • Hands-On Bash Brackets Exercises
    • 📌 1. Using [ ] and [[ ]] for Condition Checking
    • 📌 2. Using {} for Brace Expansion
    • 📌 3. Using () for Subshells
    • 📌 4. Using $(( )) for Arithmetic Operations
    • 📌 5. Using $( ) for Command Substitution
    • 📌 6. Using ${} for String Manipulation
    • 📌 7. Using [[ ]] for Regex Matching
    • 📌 8. Using {} for Grouping Commands
    • 📌 9. Using $( ) and $(( )) Together
    • 📌 10. Using Brackets for File Processing

📌 Key Highlights of  Bash Brackets

Bracket Type Usage Example
[] Basic test conditions [ -f file.txt ]
[[ ]]  more advanced features compared to

single brackets, including regular expression

[[ $str == Jo* ]]
() Subshell execution (cd /tmp && ls)
$(( )) Arithmetic operations y=$((x + 10))
{} Command grouping,Variable expansion & loops echo {1..5}
$( ) Command substitution today=$(date)
${} String manipulation ${#str} (length)

📌 1. Square Brackets [] (Test Conditions)

Used for evaluating conditions, similar to the test command.

✅ Example 1: Check if a File Exists

bash
if [ -f "file.txt" ]; then
echo "File exists"
else
echo "File does not exist"
fi

🔹 Use case: Check if file.txt exists.


✅ Example 2: String Comparison

bash
str="Hello"
if [ "$str" = "Hello" ]; then
echo "Strings match"
fi

🔹 Use case: Compare two strings.


✅ Example 3: Integer Comparisons

bash
num=10
if [ "$num" -gt 5 ]; then
echo "Number is greater than 5"
fi

🔹 Use case: Compare integers (-eq, -ne, -gt, -lt, -ge, -le).


📌 2. Double Square Brackets [[ ]] (Advanced Test Conditions)

[[ ... ]] provides enhanced string comparison and supports regex.

✅ Example 4: String Matching with Wildcards

bash
name="JohnDoe"
if [[ "$name" == Jo* ]]; then
echo "Name starts with Jo"
fi

🔹 Use case: Pattern matching (*, ?, [ ] work like globbing).


✅ Example 5: Regex Matching

bash
if [[ "hello123" =~ [0-9]+ ]]; then
echo "String contains numbers"
fi

🔹 Use case: Use regex inside conditions.


📌 3. Parentheses () (Command Grouping & Subshells)

Used for grouping commands or executing in a subshell.

✅ Example 6: Grouping Commands

bash
(cd /tmp && ls) # Runs in a subshell

🔹 Use case: Changes directory temporarily without affecting the current shell.


✅ Example 7: Background Process

bash
(sleep 5; echo "Done") &

🔹 Use case: Runs commands in the background.


📌 4. Double Parentheses $(( )) (Arithmetic Operations)

Used for integer arithmetic operations.

✅ Example 8: Basic Arithmetic

bash
x=5
y=$((x + 10))
echo "Result: $y"

🔹 Use case: Perform addition, subtraction, multiplication, division.


✅ Example 9: Increment & Decrement

bash
x=10
((x++)) # Increment
((x--)) # Decrement

🔹 Use case: Shorthand for x=x+1 or x=x-1.


📌 5. Curly Braces {} (Variable Expansion & Loops)

Used for variable expansion, command grouping, and brace expansion.

✅ Example 10: Variable Expansion

bash
name="World"
echo "Hello, ${name}!"

🔹 Use case: Avoid ambiguity in variable names.


✅ Example 11: Looping with Brace Expansion

bash
echo {1..5}

🔹 Use case: Expands to 1 2 3 4 5.


✅ Example 12: Multiple Command Execution

bash
{ echo "First"; echo "Second"; } > output.txt

🔹 Use case: Group commands without creating a subshell.


📌 6. Command Substitution $( )

Used to store the output of a command in a variable.

✅ Example 13: Store Command Output

bash
today=$(date +"%Y-%m-%d")
echo "Today is $today"

🔹 Use case: Store date command output.


✅ Example 14: Using Command Substitution in a Loop

bash
for file in $(ls *.txt); do
echo "Processing $file"
done

🔹 Use case: Loop through files.


📌 7. Dollar Sign & Curly Brackets ${} (Variable Manipulation)

Used for string modifications.

✅ Example 15: Get String Length

bash
str="Hello"
echo "Length: ${#str}"

🔹 Use case: Get the length of a string.


✅ Example 16: Remove Part of a String

bash
filename="document.txt"
echo "${filename%.txt}" # Removes .txt

🔹 Use case: Extract filename without extension.


🔥 Bash Brackets Interview Questions & Answers

Brackets ([], [[ ]], {}, (), $(( )), $( ), ${}) are commonly used in Bash scripting for different operations. Here are top interview questions on Bash brackets with detailed answers.


📌 Basic Questions

1️⃣ What is the difference between [ ] and [[ ]] in Bash?

✅ Answer:

  • [ ] is a POSIX-compliant test command (same as test).

  • [[ ]] is a Bash built-in, supporting regex, pattern matching, and logical operators.

📌 Example:

bash
var="hello"
[ "$var" = "hello" ] && echo "POSIX test"
[[ "$var" == hello ]] && echo "Bash test"

📌 Key Differences:

Feature [ ] [[ ]]
String Comparison = ==
Logical Operators -a, -o &&, `
Pattern Matching ❌ ✅ (== pattern*)
Regex Support ❌ ✅ (=~ regex)

2️⃣ What is the use of {} in Bash?

✅ Answer:

  • Brace expansion for sequences {1..5}.

  • Variable expansion ${var}.

  • Grouping commands { cmd1; cmd2; }.

📌 Examples:

bash
echo {1..5} # Output: 1 2 3 4 5
echo "Hello ${USER}!" # Expands variable
{ echo "First"; echo "Second"; } > output.txt # Group commands

3️⃣ What is the difference between ( ) and { } in Bash?

✅ Answer:

  • ( ) creates a subshell (isolated execution).

  • { } groups commands without a subshell.

📌 Example:

bash
(cd /tmp && ls) # Runs in subshell (directory change is temporary)
{ cd /tmp && ls; } # Runs in the same shell (directory change persists)

📌 Intermediate Questions

4️⃣ How do $(( )) and $( ) differ in Bash?

✅ Answer:

  • $(( )) is used for arithmetic operations.

  • $( ) is used for command substitution.

📌 Examples:

bash
echo $((5 + 10)) # Output: 15 (Arithmetic)
echo "Today is $(date +%Y-%m-%d)" # Command substitution

5️⃣ What happens if you don’t use curly braces ${} for variables in Bash?

✅ Answer:
Without curly braces, ambiguity can occur.

📌 Example (Incorrect Use):

bash
file="data"
echo "$file123" # Will not work (Bash tries to expand `$file123`)

📌 Correct Use:

bash
echo "${file}123" # Expands correctly to "data123"

6️⃣ How do you use [[ ]] for pattern matching?

✅ Answer:
You can use == with wildcards inside [[ ]].

📌 Example:

bash
var="hello123"
if [[ $var == hello* ]]; then
echo "Starts with hello"
fi

📌 Key Features:

  • == allows wildcards (*, ?).

  • =~ allows regular expressions.


📌 Advanced Questions

7️⃣ How do you use [[ ]] with regex?

✅ Answer:
Use =~ inside [[ ]] for regex matching.

📌 Example:

bash
var="abc123"
if [[ $var =~ [0-9]+ ]]; then
echo "Contains numbers"
fi

🚀 Tip: No need to quote the regex!


8️⃣ How do you compare numbers correctly in Bash?

✅ Answer:
Use arithmetic comparison operators (-eq, -ne, -gt, -lt).

📌 Incorrect:

bash
if [[ $num > 5 ]]; then # WRONG: This is a string comparison!

📌 Correct:

bash
if [[ $num -gt 5 ]]; then # Correct: Numeric comparison

9️⃣ How do you use brace expansion {} in Bash loops?

✅ Answer:
You can expand ranges using {}.

📌 Example:

bash
for i in {1..5}; do
echo "Number: $i"
done

🔹 Output:

javascript
Number: 1
Number: 2
...

🔟 How do you use ${} for string operations?

✅ Answer:
Bash provides built-in string manipulation.

📌 Examples:

bash
str="hello world"
echo ${#str} # Get length (Output: 11)
echo ${str:0:5} # Substring (Output: hello)
echo ${str/world/universe} # Replace (Output: hello universe)

🔥 Bonus: Quick Comparison Table

Bracket Type Use Case Example
[ ] Basic test [ -f file.txt ]
[[ ]] Advanced test [[ $str == hello* ]]
{} Expansion & grouping echo {1..5}
() Subshell execution (cd /tmp && ls)
$(( )) Arithmetic operations y=$((x + 10))
$( ) Command substitution today=$(date)
${} Variable manipulation ${#str} (length)

Hands-On Bash Brackets Exercises

These exercises will help you practice different types of brackets ([], [[ ]], {}, (), $(( )), $( ), ${}) in Bash scripting.


📌 1. Using [ ] and [[ ]] for Condition Checking

🔹 Task:

  • Write a script to check if a file exists and is not empty using [ ].

  • Modify it to use [[ ]] instead.

📌 Example Output:

arduino
File exists and is not empty!

📌 2. Using {} for Brace Expansion

🔹 Task:

  • Create a script that generates file names:

    • file1.txt, file2.txt, file3.txt, ... file5.txt

  • Use {} for sequence expansion.

📌 Example Output:

file1.txt file2.txt file3.txt file4.txt file5.txt

📌 3. Using () for Subshells

🔹 Task:

  • Run pwd before and after changing to /tmp inside a subshell.

  • Print both results.

📌 Expected Output:

pgsql
Current Directory: /home/user
Inside Subshell: /tmp
Back to Original: /home/user

📌 4. Using $(( )) for Arithmetic Operations

🔹 Task:

  • Write a script that takes two numbers from the user and performs:

    • Addition, Subtraction, Multiplication, and Division.

  • Use $(( )) for calculations.

📌 Example Output:

yaml
Enter first number: 10
Enter second number: 5
Sum: 15
Difference: 5
Product: 50
Quotient: 2

📌 5. Using $( ) for Command Substitution

🔹 Task:

  • Print today’s date and time inside a sentence.

  • Use $(date) for command substitution.

📌 Example Output:

mathematica
Today is Sunday, March 24, 2025, at 12:30 PM

📌 6. Using ${} for String Manipulation

🔹 Task:

  • Store a full name in a variable and perform:

    • Extract first name.

    • Convert to uppercase.

    • Get length of the name.

📌 Example Output:

yaml
Full Name: John Doe
First Name: John
Uppercase: JOHN DOE
Name Length: 8

📌 7. Using [[ ]] for Regex Matching

🔹 Task:

  • Write a script that checks if a given string contains numbers using regex (=~).

📌 Example Output:

csharp
Enter a string: hello123
Contains numbers!

📌 8. Using {} for Grouping Commands

🔹 Task:

  • Write a script that:

    • Runs echo "Hello" and ls inside {}.

    • Redirects both outputs to a file.

📌 Expected Behavior:

  • Both Hello and the ls output should be saved in output.txt.


📌 9. Using $( ) and $(( )) Together

🔹 Task:

  • Get current year using $(date +%Y).

  • Calculate the year when the user will turn 100 years old.

📌 Example Output:

yaml
Enter your birth year: 1990
You will turn 100 in the year 2090.

📌 10. Using Brackets for File Processing

🔹 Task:

  • Read a file line-by-line using a while loop and:

    • Print only lines longer than 5 words.

  • Use awk inside $( ) to count words.

📌 Example Output:

vbnet
Skipping: Hello
Processing: This is a long sentence.
Processing: Another example line with words.

Primary Sidebar

Linux sysadmin tutorials linux system administrator

  • top 10 apt & apt-get commands (most used) apt vs apt-get
  • If-Else Statements in Shell Scripting
  • linux commands pdf (files & Directories, zip & unzip process, search etc)
  • Find Files with Specific Text on Linux grep find command
  • linux performance tuning inode limit file descriptors tco, kernel etc
  • Variables and Data Types in Shell Scripting
  • Top 10 most used Cat commands with examples (create, view, append files)
  • Ip tables / ufw / firewall d commands for block port ip rate limiting
  • Top 10 zip / tar commands to compress & extract files in linux
  • TOP 10 mv & cp commands in linux to move & copy files in Linux
  • Top 10 GREP Commands in linux to search files directory words strings
  • lsof netstat commands to know listening ports in linux 3 ways
  • Upgrade Ubuntu from 18.04 (19.10) to 20.04 LTS command line or gui server | desktop
  • 3 Ways (SCP, rsync, Sftp) linux server migration between two remote server apache nginx
  • linux system specs commands (CPU, Memory, Disk )speed, type. manufacture
  • linux sysctl command tweaks & hardening
  • linux security limits.conf deciding user limits process limits for nginx server
  • ulimit linux unlimited command unlimto set & know user limits open files file descriptor max user process etc.
  • red hat linux certification cost jobs salary syllabus courses fees
  • ufw firewall commads allow port enable disable ubuntu 20.04
  • ddos attack prevention
  • change ssh port in linux - avoid sshd ddos attacks
  • ping command
  • memcached install ubuntu wordpress
  • check linux version (lsb_release -a) ubuntu debian 32 or 64 bit
  • rsync command linux with examples comparison to scp
  • how to uninstall package in linux ubuntu rpm, yum apt-get
  • increase open file limit linux File descriptor ft nginx , mysql, lemp
  • remove repository ubuntu
  • htop commad memory details virtual vs shard vs resident
  • chown command in Linux with Examples
  • Kill PHP process
  • VIrtual Memory vs RSS Memory vs Shared memory in Linux
  • oom killer fixing it by configuration linux ubuntu
  • Install Lemp nginx mysql php fpm Stack on Debian 11 with repository
  • connect two remote servers linux command line
  • auto start after oom killer Mysql & php fpm nginx etc ubuntu wth systemd or cron job
  • load average Linux 1, 5, 15 min 2,4,8 cores explained
  • Control Structures in Shell Scripting
  • Shell Scripting Roadmap for Beginners to Advanced
  • awk commands with practical examples
  • Shell Scripting Tutorial for Beginners 🚀
  • find Command in Linux with Examples
  • sed Command in Linux with Examples (Beginner to Advanced)
  • Linux Text processing commands in with Examples
  • linux disk management commands
  • fdisk command in linux with examples
  • how to add a new disk in linux
  • Linux mount Command with Examples
  • fstab options with examples
  • Top 50 Shell Scripting Interview Questions and Answers
  • Linux Networking Interview Questions and Answers
  • Linux Networking Commands Cheat Sheet with Examples pdf
  • Netstat & SS Commands cheat sheet with examples Interview Questions
  • Nmap Cheat Sheet – Network Scanning & Security
  • Bash Brackets ([], (), {}, $( ), $(( ))) – Types, Uses & Examples

hi i am raju ginni, primalry i manage wordpress websites on GCP cloud platform as a cloud engineer, and create content on passionate things.
you can follow me on youtbe

© 2025 - All Rights Reserved Disclaimer & Privacy Policy