Skip to content

Writing simple shell scripts to accept input from the user and display a message on screen

Here is a simple guide to writing shell scripts that accept user input and display a message on the screen.


Example 1: Greeting Script

This script asks the user for their name and greets them.

#!/bin/bash

# Prompt the user for their name

echo “Enter your name:”

read user_name

# Display a greeting message

echo “Hello, $user_name! Welcome to the world of shell scripting.”

How to Run:

  1. Save the script as greet.sh.
  2. Make it executable:

chmod +x greet.sh

  • Run the script:

./greet.sh

Output Example:

Enter your name:

Alice

Hello, Alice! Welcome to the world of shell scripting.


Example 2: Age Checker

This script checks if the user is an adult based on their age.

#!/bin/bash

# Prompt the user for their age

echo “Enter your age:”

read user_age

# Check if the user is 18 or older

if [ $user_age -ge 18 ]; then

    echo “You are an adult!”

else

    echo “You are not an adult yet!”

fi

Output Example:

Enter your age:

20

You are an adult!


Example 3: Simple Math

This script takes two numbers from the user and calculates their sum.

#!/bin/bash

# Prompt the user for two numbers

echo “Enter the first number:”

read num1

echo “Enter the second number:”

read num2

# Perform addition

sum=$((num1 + num2))

# Display the result

echo “The sum of $num1 and $num2 is $sum.”

Output Example:

Enter the first number:

5

Enter the second number:

10

The sum of 5 and 10 is 15.


Example 4: Favorite Color

This script asks the user for their favorite color and displays a custom message.

#!/bin/bash

# Prompt the user for their favorite color

echo “What is your favorite color?”

read color

# Display a message

echo “Wow! $color is a beautiful color!”

Output Example:

What is your favorite color?

Blue

Wow! Blue is a beautiful color!


Tips for Writing and Running Shell Scripts

  1. Shebang Line (#!/bin/bash):
    1. This specifies the shell interpreter to use.
  2. read Command:
    1. Captures user input and stores it in a variable.
  3. echo Command:
    1. Prints messages to the screen.
  4. Make Executable:
    1. Use chmod +x script_name.sh to make the script executable.
  5. Run the Script:
    1. Use ./script_name.sh to execute the script.

By combining read, echo, and conditional statements, you can create interactive shell scripts to handle a variety of inputs and scenarios!