Reading Input
Read -p.
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.

- 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.
#!/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.
./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.
| key | value |
|---|---|
| Arguments | good for automation |
| read -p | good for people |
| read -s | hide the answer, like a password |
| Both | argument, 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