How to upload local changes to a forked GitHub repository using command line?

I need help uploading my local project files to a GitHub repo that I forked from someone else. When I try to push my changes, I keep getting an error message.

Here’s what I’m doing in the terminal:

cd Documents
cd myproject
git init
git add .
git commit -m "initial commit"
git remote add origin <repository-url>
git push -u origin main

But I get this error:

remote: Updates were rejected because the remote contains work that you do not have locally. This is usually caused by another repository pushing to the same ref. You may want to first integrate the remote changes before pushing again.

What’s the right way to push my local work to a forked repository? I’m working on Linux and using the command line. Do I need to pull first or is there another step I’m missing?

You’re encountering this error because you started a fresh git repo in your local folder, which created a totally different commit history from your forked repo. Your local git has no clue about the commits already sitting in the remote fork. Just pull the existing commits from your forked repo first, then push. Run git pull origin main --allow-unrelated-histories to merge the remote history with your local changes. That flag tells git to merge two repos that don’t share a common ancestor. Once the merge finishes, you’ll be able to push without hitting that rejection error.

You’re encountering this issue because using git init in an existing project folder generates a separate commit history. Instead, clone your forked repository directly using git clone <your-forked-repo-url>. Once you do that, navigate into the cloned directory, copy your local files there, and then execute git add ., followed by committing and pushing your changes. This approach retains the connection to the original history and prevents conflicts.