Helpful git commands

The version control system git is free, offers lots of possibilities, and is open source. Newbies need some time to understand git and to know the most important git commands for the daily work. Unfortunately, that is sometimes not enough, and that is why this blog post bundles helpful information around git.

Git commands
Git commands

Important setup and init steps for git

First, configure the user information once for all local repositories:

# User name and email identify the user in the version history
git config --global user.name "firstname lastname"
git config --global user.email "email address"

Next, create a .gitignore-file for each local repository that will contain all files and folders which git should ignore. For example, you will not want to track the folder node_modules in Node.js projects.

node_modules
tsconfig.json
ts_test
sapui5_1.87.0
coverage

Then, initialize an existing directory as git repository, clone a remote repository, or add a remote repository:

# Initialize a git repository
git init

# Clone a remote git repository
git clone [URL]

# List all remote branches for switching between them
git branch -a

# Add remote repository and get (fetch & merge) remote repository
git remote add [alias] [URL]
git pull

Most important git commands

Currently, these are the most important git commands in my daily work:

# Add all files to the next commit (stage)
git add *

# Commit the staged files
git commit -m "message"

# Transmit local commit to remote repository
git push [alias] [branch]

# Create a new branch
git branch [name]

# Switch to another branch
git checkout [name of a branch]

# Merge another branch into the current branch
git merge [name of a branch]

Troubleshooting

It could sometimes happen that you are using the wrong remote URL, for example when you have cloned a remote git repository, or you have to re-authenticate to GitHub (personal access token). The following git commands are helpful in such situations.

# List the current configuration
git config --list

# Remove the remote repository
git remote remove origin

# Set remote repository by using GitHub personal access token
git remote set-url origin https://<TOKEN>@github.com/<USER NAME>/<REPOSITORY>.git

In conclusion, there are much more helpful commands which you will need from time to time. The following pages, which I have added to my bookmarks, contain more commands and details:

[1] git – the simple guide (in different languages available)
[2] GitHub: Git cheat sheet (PDF)
[3] git reference
[4] Untrack files already added to git repository based on .gitignore

Leave a Reply

%d bloggers like this: