Skip to content

Latest commit

 

History

History
61 lines (42 loc) · 2.03 KB

3.md

File metadata and controls

61 lines (42 loc) · 2.03 KB

Chapter 4: The Conditional Conundrums 🤔

3 - Logical operations based on user's input

Logical Operations Based on User's Input

In Linux shell scripting, logical operations are frequently used to make decisions based on user input. These operations allow scripts to evaluate conditions and execute different code paths accordingly. Here's how you can perform logical operations based on user input, along with examples:

Reading User Input

Before performing logical operations based on user input, you need to read input from the user. This can be done using the read command, which reads a line from standard input and assigns it to a variable.

Example:

echo "Enter your age:"
read AGE

Logical Operations

Once you have obtained user input, you can use logical operators such as -eq (equal), -ne (not equal), -lt (less than), -gt (greater than), -le (less than or equal to), and -ge (greater than or equal to) to perform comparisons.

Example:

if [ "$AGE" -ge 18 ]; then
    echo "You are an adult."
else
    echo "You are a minor."
fi

Using Logical AND (&&) and OR (||) Operators

You can also use logical AND (&&) and OR (||) operators to combine multiple conditions.

Example:

echo "Enter your name:"
read NAME

if [ "$AGE" -ge 18 ] && [ "$NAME" != "" ]; then
    echo "Welcome, $NAME! You are an adult."
else
    echo "Please provide a valid name and age."
fi

Examples of Logical Operations Based on User Input

Here are some common scenarios where logical operations based on user input are used:

  • Determining if a user is eligible for voting based on age.
  • Validating user input for form fields such as name, email, and phone number.
  • Implementing access control based on user roles and permissions.

Conclusion

Logical operations based on user input provide a flexible way to create interactive and responsive shell scripts tailored to user requirements.

⬅️Previous-----------Next ➡️

Table of contents 🚀