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:
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
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
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
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.
Logical operations based on user input provide a flexible way to create interactive and responsive shell scripts tailored to user requirements.