Shell Scripting: Using read to Take Input

Shell Scripting: Using read to Take Input

What is read in Shell?

✅The read command takes input from the user during the script execution.

It waits for the user to type something — and stores it inside a variable.

✅ Very useful for dynamic observability scripts where you want input during runtime.


🛠️ Basic Syntax of read

read variable_name

        

  • Prompts the user silently.
  • Saves the user’s input into the variable.

✅ Example:

#!/bin/bash

echo "Enter server name:"
read server
echo "You entered: $server"

        

✅ Output:

Enter server name:
> prod-server
You entered: prod-server

        

📚 Using read with a Custom Prompt

✅ You can show a prompt on the same line:

read -p "Enter the directory to monitor: " directory
echo "Monitoring $directory..."

        

✅ Output:

Enter the directory to monitor: /var/log
Monitoring /var/log...

        

📚 Reading Multiple Inputs

✅ You can read multiple values at once:

#!/bin/bash

read -p "Enter username and server address: " username server
echo "User: $username"
echo "Server: $server"

        

✅ Output:

Enter username and server address: admin 192.168.1.10
User: admin
Server: 192.168.1.10

        

📚 Reading Input Silently (Useful for Passwords)

✅ Hide what the user types (great for passwords):

#!/bin/bash

read -sp "Enter your password: " password
echo
echo "Password saved securely."

        

✅ Output:

Enter your password: [user types, but nothing is visible]
Password saved securely.

        

✅ -s = Silent input (no echo on terminal)


Why read Matters in Observability Automation

✅ Makes scripts interactive:

  • Ask which server to monitor
  • Ask which metric threshold to set
  • Ask for credentials securely


More dynamic → less hardcoded scripts → more flexibility in production


🛠️ Real Observability Example Using read

#!/bin/bash

read -p "Enter server IP to monitor: " server_ip

ping -c 2 $server_ip

if [ $? -eq 0 ]; then
  echo "✅ Server $server_ip is reachable."
else
  echo "❌ Server $server_ip is DOWN!"
fi

        


Small scripts like this save SRE teams during incident response!


🧠 Simple Analogy

Learning read is like installing a touchpad on your robot 🤖:

  • Without read → robot blindly follows hardcoded instructions.
  • With read → robot asks for live input and adapts immediately.


Input on-the-go = smarter scripts = better automation.


Article content

🗺️ Where Are We in the Journey?

Linux Fundamentals → Kubernetes Observability → Shell Basics → Conditions → Loops → Functions → Error Handling → (Now) Dynamic User Input with `read`

        


You are no longer just running scripts — you are building smart, interactive systems.

To view or add a comment, sign in

More articles by Anamika Sanjay

Explore topics