65 lines
948 B
Markdown
65 lines
948 B
Markdown
|
|
# User Input
|
||
|
|
|
||
|
|
You've outputted variable values. Now, let's get input from the user.
|
||
|
|
|
||
|
|
First, create your script file:
|
||
|
|
|
||
|
|
```bash
|
||
|
|
touch shinobi.sh
|
||
|
|
```
|
||
|
|
|
||
|
|
Next, open `shinobi.sh` and add this:
|
||
|
|
|
||
|
|
```bash
|
||
|
|
#!/usr/bin/env bash
|
||
|
|
|
||
|
|
echo "What is your name?"
|
||
|
|
read name
|
||
|
|
|
||
|
|
echo "Hi there $name"
|
||
|
|
echo "Welcome to Shinobi!"
|
||
|
|
```
|
||
|
|
|
||
|
|
Save and exit the file.
|
||
|
|
|
||
|
|
Make it executable:
|
||
|
|
|
||
|
|
```bash
|
||
|
|
chmod +x shinobi.sh
|
||
|
|
```
|
||
|
|
|
||
|
|
Run your script:
|
||
|
|
|
||
|
|
```bash
|
||
|
|
./shinobi.sh
|
||
|
|
```
|
||
|
|
|
||
|
|
The script will prompt you:
|
||
|
|
|
||
|
|
```
|
||
|
|
What is your name?
|
||
|
|
Troy
|
||
|
|
```
|
||
|
|
|
||
|
|
Enter a name (e.g., `Troy`) and hit Enter. You'll see:
|
||
|
|
|
||
|
|
```
|
||
|
|
Hi there Troy
|
||
|
|
Welcome to Shinobi!
|
||
|
|
```
|
||
|
|
|
||
|
|
This script prompts the user, stores their input in the `name` variable, then uses it to print a personalized message.
|
||
|
|
|
||
|
|
### Streamlined Input
|
||
|
|
|
||
|
|
To reduce lines, use `read` with the `-p` flag. This prints a prompt before waiting for input:
|
||
|
|
|
||
|
|
```bash
|
||
|
|
#!/usr/bin/env bash
|
||
|
|
|
||
|
|
read -p "What is your name? " name
|
||
|
|
|
||
|
|
echo "Hi there $name"
|
||
|
|
echo "Welcome to Shinobi!"
|
||
|
|
```
|