Govur University Logo
--> --> --> -->
...

Write a shell script that takes user input and performs specific operations based on that input.



A shell script is a powerful tool for automating tasks in a Unix-like operating system, and it can interact with users by taking input and performing operations based on that input. Let's explore how to write a shell script that accomplishes this.

To start, we'll use the Bash shell as it is commonly available on Unix-like systems and provides rich functionality for user interaction. Here's an example of a shell script that takes user input and performs specific operations:

```
bash`#!/bin/bash

# Prompt the user for input
read -p "Enter your name: " name

# Perform operations based on user input
echo "Hello, $name! Welcome to the shell scripting world."

# Ask for a number
read -p "Enter a number: " number

# Perform calculations based on the number
if [[ $number -gt 10 ]]; then
echo "The number you entered is greater than 10."
elif [[ $number -lt 10 ]]; then
echo "The number you entered is less than 10."
else
echo "The number you entered is equal to 10."
fi`
```
In this script, we first use the `read` command to prompt the user for their name and store it in the `name` variable. The `-p` option allows us to provide a prompt to the user. We then use the `echo` command to display a welcome message using the entered name.

Next, we ask the user to enter a number using another `read` command. We store the input in the `number` variable. The script then performs calculations based on the entered number using an `if-elif-else` statement.

If the number is greater than 10, it prints a message indicating that. If the number is less than 10, it prints a different message. If the number is exactly 10, it provides a third message. The comparisons are done using the `-gt` (greater than), `-lt` (less than), and `-eq` (equal to) operators.

To execute the script, save it to a file (e.g., `user_input_script.sh`), make it executable (`chmod +x user_input_script.sh`), and then run it (`./user_input_script.sh`).

When executed, the script will prompt the user for their name and a number, perform the specified operations based on the input, and provide the corresponding output.

By leveraging user input, shell scripts can be customized and made interactive. They can perform various operations based on different inputs, enabling users to control and interact with the script's behavior. This flexibility makes shell scripting a valuable tool for automating tasks while incorporating user input and decision-making capabilities.