Variables, Branching and Loops
Fundamentals of Variables, Conditional Branching, and Loops
Objectives:
Understand how to declare and use variables in Bash.
Learn how to use conditional statements (
if
,else
,elif
).Explore loops (
for
,while
) for iterating through data.Apply these concepts in a real-world example.
2.1 Variables in Bash
Declaring Variables
In Bash, you can declare a variable by simply assigning a value to it. There is no need to specify the variable type.
Note: Do not add spaces around the =
sign when assigning values.
Accessing Variables
To access the value of a variable, use the $
symbol:
2.2 Conditional Branching
Conditional statements allow you to execute different actions based on certain conditions.
Using if
, else
, and elif
The syntax for conditional branching is as follows:
Example: Checking Age
2.3 Loops in Bash
Loops allow you to execute a block of code multiple times.
Using for
Loops
A for
loop can iterate over a list of items.
Using while
Loops
A while
loop continues as long as a condition is true.
2.4 Real-World Example: User Registration
Let’s create a simple script that simulates a user registration process. The script will collect user information, check if the user is old enough to register, and provide feedback.
Example Script: user_registration.sh
How to Run the Script
Make the script executable:
Run the script:
2.5 Summary
In this chapter, you learned about:
Variables in Bash and how to declare and access them.
Conditional statements for making decisions based on conditions.
Loops for executing code multiple times.
A real-world example that combines these concepts in a user registration scenario.
Exercises:
Modify the user registration script to include a username and validate its length.
Add a loop to allow the user to register multiple accounts until they choose to exit.
Feel free to adjust any parts of the chapter or the example to better fit your teaching style or audience! Let me know if you need any further details or modifications.
Last updated