Coding for All
Lesson 3: Asking a Question
Asking a Question Let the script ask the person running it for an answer.
1#!/bin/bash
2read -p "What is your name? " name
3echo "Nice to meet you, $name!"
Terminal
$ ./greet.sh
What is your name? Ada
Nice to meet you, Ada!
Every line, explained
#!/bin/bash
This first line is called the shebang (from "hash bang", the # and ! it starts with). It is not a comment: it tells the computer which program should read the rest of the file. #!/bin/bash means "run this with bash". Every bash script starts with this exact line.
read -p "What is your name? " name
read stops the script and waits for somebody to type an answer and press Enter, then stores it in the variable you named. The -p flag ("prompt") prints the question first. The space before the closing quote is deliberate: it leaves a gap between the question mark and where the answer is typed.
echo "Nice to meet you, $name!"
Whatever was typed is now in the name box, so the script can greet anybody. In the terminal below, somebody called Ada answers.