Search code examples
gitgit-commit

How do I make a branch on Github, make sure it is created, and push to it?


I'm writing a script to automate initializing, adding, and pushing projects to GitHub to teach myself some scripting. I get a few errors, but one of them seems to be stopping the script from working:

error: src refspec main does not match any
error: failed to push some refs to 'https://github.com/fakename/repo_name'

I''ve looked this up and it seems the script thinks there is no branch to push files to, however I do have the necessary code to create a remote repo and branch to push to. Here is my code:

# get target file name
FILE="usr/theowner/Programming/Testing/github_script/repo_name"
f="$(basename "$FILE")"

# make a github repo using the filename
gh repo create "$f" --private
echo Created repo for "$f"!

#add file within folder to now established repo
echo 
cd "$f"
git init
git config user.email fakename@fake.com
git add .
git config user.name fakename
git commit -m Committed using gh-repo.sh
git remote add origin https://github.com/fakename/"$f"
git branch -M main
git checkout -b main
git push origin main
echo Pushed files to "$f"!

These are the other two errors I encounter, but the rest of the script seems to run despite these errors anyway:

error: pathspec 'using' did not match any file(s) known to git
error: pathspec 'gh-repo.sh' did not match any file(s) known to git

Solution

  • git commit -m accepts one parameter — message. Other parameters (using gh-repo.sh) are interpreted as files. To fix the problem pass the message as one parameter using double (or single) quotes:

    git commit -m "Committed using gh-repo.sh"
    

    The error "src refspec main does not match any" appeared after git branch -M main and git checkout -b main because neither command could create a branch — there're currently no commits in the repository and a branch is a pointer to a commit. Once you fix git commit -m "Message" there will be a commit and the rest of the script should work fine.