0

I'm trying to create a shell script with a read command, so that when I run the script, it will ask the user a yes- or no-question. If the user types yes, the script continues, and if she writes no it stops.

What is the syntax for using the read command in such a way?

I am running Ubuntu 13.04.

2
  • 1
    13.04 is end of life please upgrade; we are also not a coding site but I would not advice asking this on stackoverflow.com Here is a starter: stackoverflow.com/questions/226703/…
    – Rinzwind
    Jun 8, 2014 at 18:49
  • This also barely has anything to do with Ubuntu. This is just standard shell scripting, or in the case of some answers below, with bash extensions.
    – pilona
    Jun 9, 2014 at 0:03

2 Answers 2

1

You would probably be better served by the select command, which allows the user to select an option that's presented to them.

#!/usr/bin/env bash

echo "Are you sure?"
select yn in "Yes" "No"; do
    case $yn in
        Yes ) break;;
        No ) exit;;
    esac
done

# Add whatever you want to do if the user answered "yes" here

If the user answered "No", the script will exit without executing the code further down the script.

The only downside to using select is that the options are selected using numbers. So because we have two options, the user can't type "Yes", they have to type "1", etc.

1

All your bash -programming questions in one go: http://www.tldp.org/guides.html - find "Advanced Bash-Scripting Guide".

It contains a lot of examples, very easy to read ;-) - I have had some pauses in my bash usage from time to time and have therefore used it as a dictionary.

Also: bash built in:s like read has help available as in

help read

and then, a simple answer to your question:

echo -n "Y/N - Yes or No :" && read -N 1 ans && echo -e "\r$(tput el)You said $ans."

tput - prints items from the terminfo database. "man terminfo" for more.

1
  • on hold - if questions relating to bash is off topic, then at least let there be pointers off site (e.g. tldp.org above) - unless this is allowed ubuntu specific users might step out of here, and possibly flag the place as unhelpful.
    – Hannu
    Jun 10, 2014 at 20:20

Not the answer you're looking for? Browse other questions tagged .