Devon Ville
Devon Ville

Reputation: 2091

Run a loop as long as a variable is empty

I have this small script that checks if a user name and email exist in git configuration, otherwise prompt the user to enter them:

GIT_USER_EXISTS=`git config --get-regexp 'name' | awk '{print $2}'`
GIT_EMAIl_EXISTS=`git config --get-regexp 'name' | awk '{print $2}'`
while [[ -z $GIT_USER_EXISTS || -z $GIT_EMAIl_EXISTS ]]; do
    echo "User name and Email are not set in git. Please enter them now..."
    echo "First and Last name:"
    read gitUser
    git config --global user.name "$gitUser"
    echo "Email:"
    read gitEmail
    git config --global user.email "$gitEmail"
done

It doesn't work though;)

1st - it doesn't even get into the loop in the first place. My guess is that unlike grep, awk does insert some (hidden?) character to the variable. 2nd - I'm not sure if the script could recognize there are now values, since I declared the variables outside the loop. Am I wrong in this assumption?

EDIT:

I solved the 1st issue by using backticks instead of quotes for the variable names. The second issue still stands - there must be a better using than declaring the variable twice?! something along the lines of do...while in shell?

EDIT #2:

This does the trick a little bit better, but has a rather long conditional statement. Could it possibly be any shorter?

while [[ -z $GIT_USER_EXISTS || -o $GIT_USER_EXISTS || -z $GIT_EMAIl_EXISTS || -o $GIT_EMAIl_EXISTS ]]; do
    echo "User name and Email are not set in git. Please enter them now..."
    echo "First and Last name:"
    read gitUser
    git config --global user.name "$gitUser"
    echo "Email:"
    read gitEmail
    git config --global user.email "$gitEmail"

    GIT_USER_EXISTS=`git config --get-regexp 'name' | awk '{print $2}'`
    GIT_EMAIl_EXISTS=`git config --get-regexp 'name' | awk '{print $2}'`
done

Actually it almost does the trick - it should be "if var is set and is empty or if var is not set". But that would be much too long:)

Upvotes: 0

Views: 96

Answers (1)

Gilles Quénot
Gilles Quénot

Reputation: 184955

Try doing this :

GIT_USER_EXISTS="git config --get-regexp 'name' | awk '{print $2}'"
GIT_EMAIl_EXISTS="git config --get-regexp 'name' | awk '{print $2}'"
while [[ -z $GIT_USER_EXISTS || -z $GIT_EMAIl_EXISTS ]]; do
    echo "User name and Email are not set in git. Please enter them now..."
    echo "First and Last name:"
    read gitUser
    git config --global user.name "$gitUser"
    echo "Email:"
    read gitEmail
    git config --global user.email "$gitEmail"
    GIT_USER_EXISTS="git config --get-regexp 'name' | awk '{print $2}'"
    GIT_EMAIl_EXISTS="git config --get-regexp 'name' | awk '{print $2}'"
done
  • if you test $GIT_USER_EXISTS or $GIT_EMAIl_EXISTS, you should declare it somewhere ;)

Upvotes: 1

Related Questions