tags:

views:

97

answers:

7

I have a shell script that I want to ask the user if they want to continue. If they type 'n' and press enter the script will exit.

If they press 'y' and enter it will continue to run. I have this at the top of my script but it continues regardless of what I type.

What am I doing wrong ?

goon=
while [ -z $goon ]
do
    echo -n 'Do you want to continue? '
    read goon
    if [[ $goon = 'n' ]]
    then
        break
    fi
    goon=
done
+2  A: 

The 'break' statement will exit you out of your while loop.

If you want to exit the script you want to use 'exit'.

Jumipo
I bet that's what his problem is.
Pointy
Maybe there's more than one. Clyfe seems to have it working with a different fix.
cazlab
A: 

Here's a working example (== instead of = for equality testing)

goon=
while [ -z $goon ]
do
    echo -n 'Do you want to continue? '
    read goon
    if [[ $goon == 'n' ]]
    then
        break
    fi
    goon=
done

Strange thing, the original works ok for me too ...

clyfe
+2  A: 

That works perfectly well for me if I get rid of the doubled square brackets:

if [ $goon = 'n' ]
Pointy
I generally limit my scripts to sh syntax, not bash, but I'll bet the doubled brackets put the conditional clauses into a subshell. Then the break would leave the subshell, but keep going in the main shell.
mpez0
I'm not really sure. Most of what I know about shell scripting is knowledge that solidified in the mid 1980's, so there are all sorts of newer features that confuse me. The bracket "syntax", back when, was achieved by making a hard link in /bin from '[' to the "test" executable.
Pointy
A: 

I'm less than positive, but it looks as though your if statement will always evaluate to false. Here's a resource on BASH coding that explains how to use conditionals in the way you are attempting to. http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-6.html#ss6.4

cazlab
Pointy beat me :], still check out that link though.
cazlab
A: 

I think you mean "exit" instead of "break", if you want the whole script to exit.

Also, you aren't actually checking for "y", so it loops forever even if they do say "y".

if [[ $goon = 'n' ]]
then
    exit
fi
if [[ $goon = 'y' ]]
then
    break
fi
David Gelhar
+1  A: 

Rather than echo + read, just use read -p

read -p  "Do you want to continue? " goon 
Sorpigal
+1  A: 

use an infinity loop and case/esac like this

while true
do
    read -r -p 'Do you want to continue? ' choice
    case "$choice in
      n|N) break;;
      y|Y) echo "do your stuff here"
    esac
done
ghostdog74