# Handy git commands

To Get list of configuration

```plaintext
git config --list
```

To set global username and email

```plaintext
git config --global --replace-all user.name "${userName}"
git config --global --replace-all user.email "${userEmail}"
```

To set local user.name and user.email different for each repo

```plaintext
git config user.name "${userName}"
git config user.email "${userEmail}"
```

To clone git repository using git token

```plaintext
git clone -b branchName https://$gittoken@ https://github.com/account/<Repo>.git
git clone https://$gittoken@ https://github.com/account/<Repo>.git
```

To create feature branch

```plaintext
git checkout -b newFeatureBranch
git push -u origin newFeatureBranch
```

To get upstream details

```plaintext
git remote -v
# or we can use
git config --get remote.origin.url
```

To change remote repository / origin

```plaintext
git remote rename origin upstream
git remote add origin URL_TO_GITHUB_REPO
git push origin master
```

To see difference of staged items

```plaintext
git diff --staged
git diff --staged folder/*
```

To discard local untracked changes to file

```plaintext
git restore <filename>
```

To discard local tracked( staged) changes to file

```plaintext
git restore --staged <filename>
```

To discard all local tracked( staged) changes

```plaintext
git reset
```

To discard last local commit : ref: [https://www.freecodecamp.org/news/git-revert-commit-how-to-undo-the-last-commit/](https://www.freecodecamp.org/news/git-revert-commit-how-to-undo-the-last-commit/)

```plaintext
git reset --soft HEAD~1
```

\====================

To change multiple old commits

Ref: https://www.w3docs.com/snippets/git/how-to-change-older-or-multiple-commits.html

Running interactive rebase Run :

```plaintext
git rebase -i HEAD~N
# N is the number of commits on which you perform a rebase.
```

For example:

```plaintext
git rebase -i HEAD~12
```

Replacing pick to reword Move to the lines of the commit message you want to change and replace pick with reword. Reword or r stops the rebase process and gives a chance to amend the commit message.

Saving changes After changing the messages save and close the editor. A new text editor opens for each chosen commit. All you need is to change the commit message, then save the file, and finally close the editor.

Force pushing Then, force push the changes to the remote repository running the following:

```plaintext
git push --force <branchname>
```

\====================

To merge changes from anotherBranch to currentBranch

```bash
git fetch --all
git checkout <anotherBranch>
git pull
git checkout <currentBranch>
git merge <anotherBranch>
```

To sync code changes from Any other ( or upstream Repository) , upstream repository could be the one from which origin was Forked.  
in this case.

```bash
git remote add upstream <upstream repo URL>
git fetch upstream
git merge upstream/<branch name>
```
