0

so I'm trying to build one of my first scripts, but it doesn't execute correctly.

I would like to git fetch --prune origin inside the script, but before that, I would like to ask the question, would you like to "continue" or "exit". The "exit" part works, but not the "continue" part.

#!/usr/bin/env bash

echo "Ready to git-some and sync your local branches to the remote counterparts ?"

REPLY= read -r -p 'Continue? (type "c" to continue), or Exit? (type "e" to exit): '

if [[ "${REPLY}" == 'c ' ]]
then
  echo "About to fetch"
  git fetch --prune origin
elif [[ "${REPLY}" == 'e' ]]
then
  echo "Stopping the script"
fi
  • «The "exit" part works, but not the "continue" part.»  Does it say Stopping the script, or does it just silently exit?  What happens if you type a letter other than “c” or “e”?  What debugging have you done?  (Hint: printing variables is a good idea 107% of the time.) – G-Man Sep 5 '18 at 6:32
  • @G-Man it was saying the "Stopping the script". Had not done any debugging, but (mind blowing) just realised that I could actually do print MY_VAR_NAME thanks for that :) – intercoder Sep 5 '18 at 7:17
3

you have space in first if condition 'c ':

if [[ "${REPLY}" == 'c ' ]]

The condition looks for c[space] or e

Remove it.

if [[ "${REPLY}" == 'c' ]]

Use else condition to debug as below:

if [[ "${REPLY}" == 'c' ]]
then
    echo "About to fetch"
    git fetch --prune origin
elif [[ "${REPLY}" == 'e' ]]
then
    echo "Stopping the script"
else
    echo "${REPLY} is INVALID"
fi

I prefer to use a switch case for this kind of scenario:

echo "Ready to git-some and sync your local branches to the remote counterparts ?"

read -r -p 'Continue? (type "c" to continue), or Exit? (type "e" to exit): ' REPLY

case $REPLY in
    [Cc])
        echo "About to fetch"
        git fetch --prune origin
        ;;
    [Ee])
        echo "Stopping the script"
        exit 1;;
    *)
        echo "Invalid input"
        ;;
esac
  • thanks this works perfectly, and thanks for introducing me to the case statement in bash. :) Question, what is this [Cc] and [Ee] why the capital letters before? – intercoder Sep 5 '18 at 7:15
  • to validate both the cases, user can pass arg as C or c. you can remove the upper case if you dont require. – msp9011 Sep 5 '18 at 7:17
  • case uses the same kind of patterns like filename globs. So you could also use say [Cc]* to accept any trailing garbage, if you so wish. – ilkkachu Sep 5 '18 at 7:40
  • thanks folks !!! Will try to create another script now ;) – intercoder Sep 5 '18 at 7:41
  • 1
    @SivaPrasath just did :) – intercoder Sep 5 '18 at 9:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.