Git provides a various set of commands to operate the repository on our local setup. Eg.
git clone to copy the repo from the upstream,
git status to check what files, etc are changed,
git commit to save our changes,
pull to update and retrieve from the upstream. Here are some other useful git commands which are mostly used by users in following cases.
Get Log of specific part in a file
To get the changes that are done to a specific part of your file, we can make use of
-L options provided by
git log. It can be used as -
$ git log -u -L <upperLimit>,<lowerLimit>:<path_to_filename>
-u is the first line and
-L is used to specify the end line of the part for which we intend to see the changes.
Error - You need to resolve your current index first
This error normally doesn't let us change the branch of the git on the terminal. If you don't want any of the merges listed in git status and want to get rid of the error, try using the below command -
$ git reset --merge
This resets the index and updates the files in the working tree that are different between
HEAD, but keeps those which are different between the index and working tree (i.e. which have changes which have not been added).
Add and Remove remote from Git
You can easily view a list of remotes added to your git folder by
git remote OR
git remote -v. To add a new remote of an upstream to your git, use
add option as below -
$ git remote add <remote_name> <upstream git url>
Similarly, simply use
rm to remove a remote from your git folder.
$ git remote rm <remote_name>
Cherry-pick a commit from Github
If you directly use a hash of a git commit to cherry-pick on your local, you may receive an error like below -
fatal: bad object <commit_hash>
You need to add a remote to your local git folder in order to cherry-pick a commit of a user. Add a remote as mentioned in the above point where
<upstream git url> is the user's repository URL. Something like -
$ git remote add <user_remote_name> <user's git repository url>
Fetch the remote so that all of its branches are known to your git dir.
$ git fetch --all OR $ git fetch <user_remote_name>
Then we can use the
cherry-pick command easily to get all the changes made by the user to our files in the directory.
$ git cherry-pick <commit_hash>
Note that when you commit and push the changes on the current branch with your additional changes, there will be two commits created on Github - One is the above user's commit and the other is your own changes made after the cherry-pick process.
Remove Untracked files from local Git
There are some local files which is not added to git are remained unrecognized by the git folder. They do appear in
Untracked Files in the result displayed by
git status. To remove all the files from the list, use
-xf option as below -
$ git clean -xf
-d in addition if you also need to delete the directories listed in Untracked Files. Check the list of option description in the documentation.