0

Ok I'm trying to have a situation where I check if a file exists, if it does then I give the user the option to download it again - I want the default (enter) to be Y, I want Y or y to continue the script, I want N or n to exit the script, and I want all other responses to go back and re-prompt the question... but I'm stuck on that.

What I've done really just continues on (enter), and fails on all other responses other than lowercase y.

Here it is:

if [ -f $target/$remote_backup ];then
    read -p "This file already exists, do you still want to download? [Y/n]" decide
     if [ -z $decide ];then
        # if you press return it'll default to Y and continue
        decide="Y"
    else
        if [ $decide != y ]; then
        echo "Ok you said no or pressed a random button, exiting"
        exit -1
    fi
fi
fi

2 Answers 2

4

The usual structure to use for this is case.

case "$decide" in
  y|Y|'') echo "yes" ;;
  n|N) echo "no" ;;
  *) echo "boo" ;;
esac
Sign up to request clarification or add additional context in comments.

4 Comments

So that goes after the read? I won't be echoing I don't think, or do I need to in this situation? can i exit -1 if they press n and how can I loop if they answer * ?
Put it inside a loop. On N, exit. On Y, break.
Tell the user to enter a valid option.
I can't get that to ask the user to enter a valid option without kicking them off the script
1

Try a while loop:

if [ -f $target/$remote_backup ]; then
    decide="?"
    while [ "$decide" != "y" -a "$decide" != "n" ]; do
        read -p "This file already exists, do you still want to download? [Y/n] " decide
        if [ -z $decide ]; then
            decide="y"
        fi
    done
    echo Decision: $decide
fi

2 Comments

I don't think I understand, does the while go in after? like this... if [ -f $target/$remote_backup ];then while [ "$decide" != "y" -a "$decide" != "n" ]; do read -p "This file already exists, do you still want to download? [Y/n] " decide if [ -z $decide ]; then decide="y" fi done
@beatbreaker, the while goes after your first if. I updated my answer with more context.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.