Peter Penzov
Peter Penzov

Reputation: 1668

Error in bash script switch case

I want to create simple witch case in which I can execute functions based on user prompts:

echo Would you like us to perform the option: "(Y|N)"

read inPut

case $inPut in
# echoing a command encapsulated by
# backticks (``) executes the command
"Y") echo 'Starting.....'
donwload_source_code


# depending on the scenario, execute the other option
# or leave as default
"N") echo 'Stopping execution'
exit
esac

But when I execute the script I get error:

Would you like us to perform the option: (Y|N)
n
run.sh: line 27: syntax error near unexpected token `)'
run.sh: line 27: `"N") echo 'Stopping execution''
EMP-SOF-LT099:Genesis Plamen$ 

Dow you know how I can fix this issue?

Upvotes: 1

Views: 576

Answers (2)

Inian
Inian

Reputation: 85550

Multiple issues.

  1. Add a ;; at end of each case construct
  2. The exit command is misplaced within the switch-case construct without the ;; present . It should be at the end of case or above.
  3. read has a own option to print the message for user prompt, can avoid a unnecessary echo.

Error-free script

#!/bin/bash

read -p "Would you like us to perform the option: \"(Y|N)\" " inPut

case $inPut in
# echoing a command encapsulated by
# backticks (``) executes the command
"Y") echo 'Starting.....'
donwload_source_code
;;


# depending on the scenario, execute the other option
# or leave as default
"N") echo 'Stopping execution'
exit
;;

esac

Upvotes: 2

LF-DevJourney
LF-DevJourney

Reputation: 28529

add ;;

#!/bin/bash
echo Would you like us to perform the option: "(Y|N)"

read inPut

case $inPut in
# echoing a command encapsulated by
# backticks (``) executes the command
"Y") echo 'Starting.....'
donwload_source_code


# depending on the scenario, execute the other option
# or leave as default
;;
"N") echo 'Stopping execution'
exit
;;
esac

Upvotes: 2

Related Questions