BudiBadu Logo
Samplebadu

Bash by Example: User Input

Bash 5.0+

How to read input from the user during script execution using the read built-in command, understanding various read options like -p for prompts and -s for silent password input, using -t for timeout to prevent indefinite blocking, reading multiple variables in one command, and implementing robust input validation patterns.

Code

#!/bin/bash

# Prompt for input
echo "What is your name?"
read name

echo "Hello, $name!"

# Prompt with a message on the same line ( -p )
read -p "Enter your age: " age
echo "You are $age years old."

# Read a password silently ( -s )
read -s -p "Enter password: " password
echo
echo "Password saved (length: ${#password})"

Explanation

Interactive scripts often need to accept user input. The read command is the standard tool for this. By default, it reads a line from standard input and assigns it to the specified variable. If no variable is provided, the input is stored in the default variable $REPLY.

The read command has several useful flags to improve the user experience. The -p flag allows you to specify a prompt string directly, keeping the input cursor on the same line. The -s flag (silent mode) prevents the user's input from being echoed to the screen, which is essential for reading sensitive data like passwords.

You can also use the -t flag to set a timeout, ensuring the script doesn't hang indefinitely if the user is away. Reading multiple variables at once is also possible; read var1 var2 splits the input line by whitespace.

Code Breakdown

5
read name pauses the script and waits for the user to type text and press Enter. The text is stored in the variable $name.
10
read -p combines the prompt echo and the read action. This is cleaner and keeps the cursor at the end of the prompt text.
14
read -s turns off local echo, so characters aren't displayed as they are typed. This is standard for password inputs.
16
${#password} calculates the length of the password string, demonstrating that the data was captured correctly despite being invisible.