PixieCatSupreme
PixieCatSupreme

Reputation: 71

Unable to get right git branch name in bash

I'm working on the post-receive of my git server so that it automatically uploads the latest version of my website in a folder named after the branch that the commit was in, but somehow doing this code doesn't work as intended.

Somehow my value branch gets the values of all the branches instead of the branch I'm trying to get. Hash does get the right hash code. I have tested it outside of the program, so does branch when I type the right hash. Did I use the wrong syntax in this program?

#!/bin/sh
hash=$(git log -n 1 --pretty=format:"%h")
branch=$(git branch --contains $(git log -n 1 --pretty=format:"%H"))
if [ branch ]
then
    GIT_WORK_TREE="/data/site/'$branch'"
    echo "/data/site/'$branch'"
    git checkout -f $branch
fi

Upvotes: 1

Views: 350

Answers (1)

PixieCatSupreme
PixieCatSupreme

Reputation: 71

Alright, I got it to work as I wanted! After hearing that post-receive got refname as stdin, found out that I had to trim down refname to get only the branch name and came up with this bit of code. Thanks guys. :)

#!/bin/sh
while read oldrev newrev refname
do
    branch=${refname##*/}
    if [ branch ]
    then
        path="/data/site/$branch"
        mkdir $path
        unset GIT_INDEX_FILE
        export GIT_WORK_TREE=$path
        git checkout -f $refname
        echo "Successfully pushed to $path"
    fi
done

Upvotes: 1

Related Questions