0
0
Bash Scriptingscripting~15 mins

test command and [ ] syntax in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the test command and [ ] syntax in Bash
📖 Scenario: You are writing a simple Bash script to check if a file exists and if a number is positive. This is common when automating tasks like backups or validations.
🎯 Goal: Build a Bash script that uses the test command and [ ] syntax to check conditions and print messages accordingly.
📋 What You'll Learn
Create a variable with a filename
Create a variable with a number
Use test command to check if the file exists
Use [ ] syntax to check if the number is greater than zero
Print messages based on the checks
💡 Why This Matters
🌍 Real World
Scripts often need to check if files exist before processing them, or validate numbers before calculations.
💼 Career
Knowing how to use <code>test</code> and <code>[ ]</code> is essential for writing reliable Bash scripts in system administration and automation roles.
Progress0 / 4 steps
1
Set up variables for file and number
Create a variable called filename and set it to example.txt. Create another variable called num and set it to 5.
Bash Scripting
Need a hint?

Use = without spaces to assign values in Bash.

2
Check if the file exists using test command
Use the test command to check if the file stored in filename exists. Store the result in an if statement.
Bash Scripting
Need a hint?

The -e option checks if a file exists.

3
Check if the number is positive using [ ] syntax
Use the [ ] syntax inside an if statement to check if the variable num is greater than zero.
Bash Scripting
Need a hint?

Use -gt inside [ ] to compare numbers.

4
Print messages based on both checks
Add an else clause to each if statement to print "File does not exist." if the file is missing, and "Number is not positive." if the number is zero or negative. Then run the script to see the output.
Bash Scripting
Need a hint?

Use else to handle the opposite condition in if statements.