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.
📌 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
🔹 Use case: Check if file.txt
exists.
✅ Example 2: String Comparison
🔹 Use case: Compare two strings.
✅ Example 3: Integer Comparisons
🔹 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
🔹 Use case: Pattern matching (*
, ?
, [ ]
work like globbing
).
✅ Example 5: Regex Matching
🔹 Use case: Use regex inside conditions.
📌 3. Parentheses ()
(Command Grouping & Subshells)
Used for grouping commands or executing in a subshell.
✅ Example 6: Grouping Commands
🔹 Use case: Changes directory temporarily without affecting the current shell.
✅ Example 7: Background Process
🔹 Use case: Runs commands in the background.
📌 4. Double Parentheses $(( ))
(Arithmetic Operations)
Used for integer arithmetic operations.
✅ Example 8: Basic Arithmetic
🔹 Use case: Perform addition, subtraction, multiplication, division.
✅ Example 9: Increment & 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
🔹 Use case: Avoid ambiguity in variable names.
✅ Example 11: Looping with Brace Expansion
🔹 Use case: Expands to 1 2 3 4 5
.
✅ Example 12: Multiple Command Execution
🔹 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
🔹 Use case: Store date
command output.
✅ Example 14: Using Command Substitution in a Loop
🔹 Use case: Loop through files.
📌 7. Dollar Sign & Curly Brackets ${}
(Variable Manipulation)
Used for string modifications.
✅ Example 15: Get String Length
🔹 Use case: Get the length of a string.
✅ Example 16: Remove Part of a String
🔹 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 astest
). -
[[ ]]
is a Bash built-in, supporting regex, pattern matching, and logical operators.
📌 Example:
📌 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:
3️⃣ What is the difference between ( )
and { }
in Bash?
✅ Answer:
-
( )
creates a subshell (isolated execution). -
{ }
groups commands without a subshell.
📌 Example:
📌 Intermediate Questions
4️⃣ How do $(( ))
and $( )
differ in Bash?
✅ Answer:
-
$(( ))
is used for arithmetic operations. -
$( )
is used for command substitution.
📌 Examples:
5️⃣ What happens if you don’t use curly braces ${}
for variables in Bash?
✅ Answer:
Without curly braces, ambiguity can occur.
📌 Example (Incorrect Use):
📌 Correct Use:
6️⃣ How do you use [[ ]]
for pattern matching?
✅ Answer:
You can use ==
with wildcards inside [[ ]]
.
📌 Example:
📌 Key Features:
-
==
allows wildcards (*
,?
). -
=~
allows regular expressions.
📌 Advanced Questions
7️⃣ How do you use [[ ]]
with regex?
✅ Answer:
Use =~
inside [[ ]]
for regex matching.
📌 Example:
🚀 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:
📌 Correct:
9️⃣ How do you use brace expansion {}
in Bash loops?
✅ Answer:
You can expand ranges using {}
.
📌 Example:
🔹 Output:
🔟 How do you use ${}
for string operations?
✅ Answer:
Bash provides built-in string manipulation.
📌 Examples:
🔥 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:
📌 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:
📌 3. Using ()
for Subshells
🔹 Task:
-
Run
pwd
before and after changing to/tmp
inside a subshell. -
Print both results.
📌 Expected Output:
📌 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:
📌 5. Using $( )
for Command Substitution
🔹 Task:
-
Print today’s date and time inside a sentence.
-
Use
$(date)
for command substitution.
📌 Example Output:
📌 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:
📌 7. Using [[ ]]
for Regex Matching
🔹 Task:
-
Write a script that checks if a given string contains numbers using regex (
=~
).
📌 Example Output:
📌 8. Using {}
for Grouping Commands
🔹 Task:
-
Write a script that:
-
Runs
echo "Hello"
andls
inside{}
. -
Redirects both outputs to a file.
-
📌 Expected Behavior:
-
Both
Hello
and thels
output should be saved inoutput.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:
📌 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: