AI Hints
Home›Linux Tutorial›Your First Scripts
Linux · Lesson 102 of 120

Reading Input

Read -p.

⏱ 2 min read▶ Video at 2:16:48🎓 Free
Watch this lesson in the Linux courseWatch on YouTube ↗Full Linux course

Sometimes a script needs to ask a question while it runs. What's your name? Which file? Are you sure? The read command waits for the user to type an answer.

Reading Input
From the video: Reading Input
  • Ask while running
  • Which file? Are you sure?
  • read waits for an answer

ask.sh

Read, dash P, then a prompt in quotes, then a variable name. Bash shows the prompt, waits for the answer, and stores it in that variable. Then we use the answers, just like any other variable.

nano ask.shbash
#!/bin/bash
read -p "What is your name? " name
read -p "Favourite food? " food
echo "Nice to meet you, $name."
echo "I like $food too!"

Answering questions

We run the script, and it asks for a name. We type Sam. Then it asks about food, and we type pizza. The script replies, using both answers.

Terminal
./ask.sh
What is your name? Sam
Favourite food? pizza
Nice to meet you, Sam.
I like pizza too!

Arguments or read?

Arguments are best when the script will be run by other scripts, or by cron, because nobody is there to answer questions. Read is friendlier for people. Many scripts use both. They take an argument if one is given, and ask if it isn't.

keyvalue
Argumentsgood for automation
read -pgood for people
read -shide the answer, like a password
Bothargument, or ask

Summary

Read dash P asks a question, and stores the answer in a variable. Use it when a person runs the script. Next, making decisions, with if.

Key takeaways
  • read -p "Question? " var
  • read -s for secrets
  • Arguments for automation
Next up: Making Decisions — if and test