How to Prompt for User Input in Bash Scripts Using the read Command

When you are writing a bash script to automate a task, such as creating a new user account or configuring a database, you often need the script to pause and ask the human operator for specific information (like a username or a password). Hardcoding these values directly into the script is inefficient and insecure. Instead, you can make your bash scripts interactive by using the Linux read command to capture keyboard input.

How the read Command Works

The read command pauses the execution of a bash script and waits for the user to type something and press Enter. It then takes whatever the user typed and saves it into a variable so your script can use it later.

Here is the most basic example of how it is used in a script:

#!/bin/bash
echo "Please enter your name:"
read USER_NAME
echo "Hello, $USER_NAME! Welcome to the server."

When you run this script, it prints the question, stops and waits for you to type your name, assigns your input to the USER_NAME variable, and then prints the personalized greeting.

Using the Prompt Flag (-p)

In the previous example, we used the echo command to ask the question before calling read. This requires two lines of code and puts the user’s cursor on a new line below the question. A cleaner, more professional method is to use the -p (prompt) flag built directly into the read command.

#!/bin/bash
read -p "Enter the IP address of the target server: " TARGET_IP
ping -c 4 $TARGET_IP

By using -p, the question and the blinking cursor stay on the exact same line, providing a much better user experience.

Securing Password Input (-s)

If your script needs to ask for a database password or an API key, you absolutely do not want the user’s keystrokes echoing across the screen for anyone walking past to see. You can combine the prompt flag (-p) with the silent flag (-s) to hide the input.

#!/bin/bash
read -sp "Enter the MySQL root password: " DB_PASS
echo "" # This adds a blank line after the user presses Enter
echo "Authenticating..."

When the -s flag is active, the user can type normally, but their keystrokes will remain completely invisible. (Note: Because the Enter key is also silent, you must manually add an empty echo "" command immediately afterward to push the terminal output down to the next line).

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.