0
0
Bash Scriptingscripting~15 mins

Why conditionals branch script logic in Bash Scripting - See It in Action

Choose your learning style9 modes available
Why conditionals branch script logic
📖 Scenario: You are writing a simple script to check if a folder exists on your computer. Depending on whether the folder is there or not, the script will print a different message. This helps you understand how conditionals can change what your script does.
🎯 Goal: Build a bash script that uses a conditional if statement to check if a folder named my_folder exists. If it exists, print Folder exists. If it does not exist, print Folder does not exist.
📋 What You'll Learn
Create a variable called folder with the value my_folder
Create a variable called exists_message with the value Folder exists
Create a variable called not_exists_message with the value Folder does not exist
Use an if statement with the test [ -d "$folder" ] to check if the folder exists
Print $exists_message if the folder exists
Print $not_exists_message if the folder does not exist
💡 Why This Matters
🌍 Real World
Scripts often need to check if files or folders exist before doing tasks like backups or installations.
💼 Career
Understanding conditionals is essential for automation, system administration, and writing reliable scripts.
Progress0 / 4 steps
1
Set up folder and message variables
Create a variable called folder and set it to my_folder. Then create two variables: exists_message with the value Folder exists and not_exists_message with the value Folder does not exist.
Bash Scripting
Need a hint?

Use the syntax variable_name="value" to create variables in bash.

2
Write the if condition to check folder existence
Write an if statement that uses [ -d "$folder" ] to check if the folder exists. Inside the if, add a comment # Folder exists. After the if, add an else with a comment # Folder does not exist.
Bash Scripting
Need a hint?

Use if [ condition ]; then ... else ... fi to write conditionals in bash.

3
Add commands to print messages inside the if and else blocks
Inside the if block, add a command to print $exists_message. Inside the else block, add a command to print $not_exists_message.
Bash Scripting
Need a hint?

Use echo "$variable_name" to print the value of a variable in bash.

4
Run the script and see the output
Run the script and observe the output. The script should print Folder exists if the folder my_folder exists, or Folder does not exist if it does not.
Bash Scripting
Need a hint?

Use bash script_name.sh to run your script in the terminal. The output depends on whether the folder my_folder exists.