Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

git - Check Bitbucket login credentials inside shell script

I'm currently writing a shell/bash script to automate a workflow. This bash script can clone projects and create new repo's on Bitbucket, do composer install/update's and more of that stuff.

My first plan was to do this all over SSH, but there are some situations that I need HTTPS. For all thinks that go's over HTTPS I need to check the user credentials for Bitbucket first. The credentials consisting of a username and password.

Is this possible. If so, how?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As you suggested in comments, curl can do HTTP Basic Auth for you. For BitBucket, the response will be 401 Unauthorized or 200 OK, depending on the validity of username/password pair. You could test the output (or only headers) with grep, but a little bit more robust approach would be to use the -w/--write-out option, combined with a HEAD request and -silenced output:

http_status=$(curl -X HEAD -s -w '%{http_code}' 
              -u "username:password" -H "Content-Type: application/json" 
              https://api.bitbucket.org/2.0/repositories/$repo_owner)

Then, to test the status, you can use a simple conditional expression:

if [[ $http_status == 200 ]]; then
    echo "Credentials valid"
else
    if [[ $http_status == 401 ]]; then
        echo "Credentials INVALID"
    else
        echo "Unexpected HTTP status code: $http_status"
    fi
fi

Or, if you plan on testing multiple status codes, you can use the case command, for example:

case $http_status in
    200) echo "Credentials valid";;
    301|302) echo "API endpoint changed";;
    401) echo "Credentials INVALID";;
    5*) echo "BitBucket Internal server error";;
    *) echo "Unexpected HTTP status code: $http_status";;
esac

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...