-5

I wrote this code in a bash script. When I run it, the prompt, "Start? [y/n]", but no matter what I respond, it just closes the window. Also, what is the proper syntax for an if statement.

@echo off
set /p choice="Start? [y/n] "
echo $choice
echo $choice$
if $choice$ == "y"
then 
goto Labelyes
fi

if $choice$ == "n"
then
exit
fi

:Labelyes
echo YAY
set /p goodbye="BYE"
if [1==1]; then exit; fi

Thank You!

  • 4
    That's not `bash`, for starters. It looks more like a DOS batch script. – chepner Dec 13 '17 at 12:54
  • Use the "read" command: https://stackoverflow.com/questions/226703/how-do-i-prompt-for-yes-no-cancel-input-in-a-linux-shell-script – BSUK Dec 13 '17 at 13:15
  • Take a basic Bash tutorial, lots around, just type "bash tutorial" into your search engine. – cdarke Dec 13 '17 at 16:13

2 Answers2

0

Bash if statement

Your script is generally incorrect so thinking about why it doesn't work does not make sense.

matiit
  • 7,969
  • 5
  • 41
  • 65
0

As commented, the syntax you have used is more like a Microsoft Windows batch (.bat) file than anything else. Below is a conversion to bash. To look at the syntax for read, type help read.

The syntax for an if statement (read man bash or this) is confusing at first. The [[ is actually a command which does pattern matching, and a simple example is shown. The pattern can only be on the right of the =. Note that == can also be used but the standard says to use =.

Simple tests can also use the test command, or [. Arithmetic tests use ((.

goto is a four-letter word and not used in polite circles (some disagree).

#!/usr/bin/env bash

#set /p choice="Start? [y/n] "
read -p "Start? [y/n] " choice

echo "$choice"
#echo $choice$

if [[ $choice = [Yy]* ]]   # Accepts y, Y, yes, Yup, etc...
then
    #goto Labelyes
    echo YAY               # Quotes are optional, but beware embedded whitespace
    #set /p goodbye="BYE"
    read -p "BYE" goodbye

elif [[ $choice == "n" ]]  # Only n   "elif" means "else if"
then
    exit
else
    # What happens if neither Y nor N were given?
    echo "Invalid response, exiting anyway"
fi

#I have no idea what this is supposed to be for
#if [1==1]; then exit; fi

You could use a case statement instead, but get the if statement understood before trying that.

cdarke
  • 42,728
  • 8
  • 80
  • 84