GIT Commands

Action Command
REPOSITORY Initialize BARE GIT repository (generally used at servers), this will have no working directory, only used for clone and merge.
By convention, repository name has .git extension. Also, bare repository does NOT have .git hidden folder.
git init --bare <repository_name>
git init --bare myproj.git

#Initialize empty GIT repository, this will create a .git hidden folder. And turns local directory to a git repository and enable version control.
git init

#To start version-controlling of your existing files, do an initial commit. See STAGING FILES & COMMITING FILES section.
CONFIGURATIONS #Post installation configure your GIT, with user name and email address, this is important because every GIT commit uses this information.
git config --global user.name "My Name"
git config --global user.email myemail@example.com

#What GIT thinks?
Check configured values for specific key.
git config <key>
git config user.name

#CONFIG EDITOR.
Set default editor of your choice, used when GIT needs you to type a message.
git config --global core.editor
Make NOTEPAD++ as default editor.
git config core.editor "'C:\Program Files (x86)\Notepad++\notepad++.exe' -multiInst -nosession"
Make EMACS as default editor.
git config --global core.editor emacs

#CONFIG DIFFTOOL.
Check available difftools on the system.
git difftool --tool-help
Set default difftool.
git config diff.tool vimdiff

#PREPARE COMMAND ALIAS.
Create shorthand for command (you use more frequently).
git config alias.<command_alias> 'execute_command'
Now, executing 'git addall' will execute 'git add .'.
git config alias.addall 'add .'

IMPORTANT:
Passing --global option configures it globally across all projects within that system(machine GIT is istalled in).
Avoid --global option, if you want to configure values for particular project.
Also, while configuring, copy/pasting of user name/email etc. may not work, type detail explicitly.
WORK STATUS #Get status of tracked/untracked files.
Files been modified, deleted, renamed etc.

git status
Shows all files of folders.
git status -u
Short status (-s/--short).
git status -s
Show ignored files as well
git status --ignored

Shows status in graphical user interface.
git gui
CODE DIFFERENCE #Compares and show changes that you have not yet staged. It shows difference in a format like the patch, as it were.

Show all file changes.
git diff
Show specific file changes.
git diff <file_name>
Show difference for all files from a commit till current local changes.
git diff <from_commit_id>
Show difference for all files between two different commits.
git diff <from_commit_id> <to_commit_id>
Show difference for specific file between two different commits.
git diff <from_commit_id> <to_commit_id> -- <file_name>
With HEAD commit traverse. For more check TRAVERSE COMMITS.
git diff HEAD HEAD^ -- <file_name>
Shows diff/status in graphical user interface.
git gui

#DIFF STAGED FILES
Show difference of staged files with respect to latest commit; --staged OR --cached.

git diff --staged <file_name>

#DIFFTOOL.
Difftool works similar to git diff but in different UI or viewing program.
See CONFIGURATIONS to check and set difftools.

Show all file changes.
git difftool
Show specific file changes.
git difftool <file_name>
Quit from vimdiff difftool.
:qa

NOTE:
Anything after -- is considered as a file.
If you have staged all of your changes, git diff will give you no output.
STAGING FILES Specific file.
git add <file_name>
Multiple files.
git add <file_name1> <file_name2> <file_name3>
Add everything under the current directory.
git add .
All files within a specific directory.
git add mydir/.
All files with extension .c.
git add *.c
All files with extension .c within a specific directory.
git add mydir/\*.c

Add everything which is already tracked.
git add -u
Add specific files which is already tracked.
git add -u mydir/.

#Unstaging files (UNDO).
git reset HEAD <file_name>

To discard changes (of tracked file) in working directory.
IMPORTANT: Anything after -- is considered as a file.

git checkout -- <file_name>
COMMITING FILES If you want to start version-controlling for existing files do an initial commit.
First stage your files and then commit files.

git commit
Commit with inline commit-message.
git commit -m "My message."

#AMMEND COMMIT.
Make additional changes you forgot in your last commit.
First stage files with additional changes, and then commit again using the --amend option.

git commit --amend
Amend-commit with inline commit-message.
git commit --amend -m "My message."

#SKIP STAGING.
git commit -a = git add + git commit.
GIT automatically stage every file that is already tracked with -a option.
git commit -a -m "My message."

Adds file differences (git diff) in the commit message.
git commit -v

NOTE:
A commit can be recognized with first 7 letters of commit-id SHA. And 'git commit' command will launch editor for writing commit-message.
At this point of time if you do not want to commit (if in VI Editor) do :!q, or commit and quit using :wq.
See CONFIGURATION section to configure editor of your choice.
COMMIT LOGS Show all logs.
git log
Show commits on specific file.
git log <file_name>
git log -- <file_name>
Show logs with Patch-output; -p OR --patch.
git log -p
Show last 4 logs.
git log -4
Logs with summarized list of files.
git log --stat
Log with ASCII graph showing your branch and merge history.
git log --graph
GIT repository browser.
git gitk

#Formatting log output with --pretty option oneline/short/full/fuller.
git log --pretty=oneline
Format with --pretty option.
git log --pretty=format:"%h - %ar by %an : %s"

#Log with TIME factors.
Log details for latest 1 week, with --since(--after) option.
git log --since=1.week
Log details post/after 1 week, with --until(--before) option.
git log --until=1.week
Other working options.
git log --until=3.day
git log --until=72.hour

Filter log details containing string within commited files.
git log -S "Matching my_string within file."
Filter log details containing string in commit message.
git log --grep "Matching my_string in a commit message."
Filter log details containing string in author entry.
git log --author="Matching my_author string."

Explore more with git help.
git help log
SEE COMMIT FILES List files in a given commit.
git diff-tree --no-commit-id --name-only -r <commit_id>
git diff-tree --no-commit-id --name-only -r 4e3761c25
SSH KEYS Generates SSH keys; -t choosing algorithm, -b key size in bits, -C comment.
ssh-keygen -t <algorithm> -b <bitsize> -C <comment>
ssh-keygen -t rsa -b 4096 -C drupal@drug.com
CLONING REPOSITORY Copy an existing GIT repository.
git clone <url>
Clone inside specific directory.
git clone <url> <dir_path>
Clone inside current directory.
git clone <url> .

Clone and checkout specific branch.
git clone --branch <branch_name> <url>

Cloning supports these protocols:
https://, git://(SSH protocol) OR user@server:path/to/repos.git (SSH protocol).
And 'git clone' command implicitly adds the origin remote for you.
COLLABORATION Collaborating with others involves managing remote repositories and sharing work by pushing and pulling data to and from these repositories.

#Show all remote references.
IMPORTANT: 'git init' OR 'git clone' command implicitly adds the origin remote for you.
git remote
Show all remote with repository URLs.
git remote -v

#Inspect remote details.
git remote show <remote_name>
git remote show origin

#Adding remote repositories.
git remote add <remote_name> <url>
git remote add my_remote https://github.com/drupal.git

#Renaming remote reference.
git remote rename <old_remote_name> <new_remote_name>
git remote rename origin ori

#Update existing remote URL.
git remote set-url <remote_name> <new_url>
git remote set-url my_remote https://newgithub.com/drupal.git

#Prevent accidental PUSH to upstream (disable push functionality)
git remote set-url --push <remote_name> DISABLED
git remote set-url --push upstream DISABLED

#Removing remote reference; remove or rm.
git remote remove <remote_name>
git remote remove my_remote

#DOWNLOAD REMOTE PROJECTS.
Download repository data along with all branches to your local repository without automatically merging it with any of your current work.
IMPORTANT: If HEAD of remote repository is 'unkown', then below command will not work.
git fetch <remote_name>

#DOWNLOAD & MERGE REMOTE PROJECTS.
Fetches and merge specified branch data into the code you are currently working on.
git pull = git fetch + git merge.
git pull <remote_name> <branch_name>

#SHARE YOUR WORK TO REMOTE PROJECTS.
When you want to share, push it upstream.
git push <remote_name> <branch_name>

IMPORTANT: If current branch is tracked with remote, then simply 'git push' and 'git push' command will pull/push the branch data.See more in BRANCH section.
git pull
git push
BRANCH Show all branches; -a OR --all.
IMPORTANT: In result, * indicates current checked-out branch.
git branch -a
Show all branches with latest commit.
git branch -v
All remote tracking branch; -r OR --remotes.
git branch -r

#CREATE BRANCH.
Create new branch.
git branch <branch_name>
Create new branch at a particular commit.
git branch <branch_name> <commit_id>
Checkout and start working on that branch.
git checkout <branch_name>

#CREATE & CHECKOUT BRANCH.
git checkout -b <branch_name> = git branch <branch_name> + git checkout <branch_name>.
git checkout -b <branch_name>
git checkout -b branch1
Create and checkout from remote branch.
git checkout -b <branch_name> <remote_name>/<branch_name>
git checkout -b my_branch my_remote/remote_branch1
Create and checkout branch at a particular commit.
git checkout -b <branch_name> <commit_id>
git checkout -b branch2 87e0e48

#DELETE BRANCH.
Delete local branch.
git branch -d <branch_name>
Delete remote-tracking local branch.
git branch -dr <branch_name>
Delete branch from remote.
git push <remote_name> -d <branch_name>

#SHARING BRANCH; you have to explicitly push branch.
Push a branch (NOT Recommended).
git push <remote_name> <branch_name>
Push branch with tracking it with remote (Recommended).
With -u option, 'git pull' and 'git push' command will get configured for the respective branch.

You can check it with 'git remote show <remote_name>' command, for more see COLLABORATION section.
git push -u <remote_name> <branch_name>

#SWITCH BRANCH.
Switch working directory with another branch.

git checkout <branch_name>
git checkout master
CHECKOUT Switch working directory with another branch.
git checkout <branch_name>
git checkout master

To discard changes (of tracked file) in working directory.
IMPORTANT: Anything after -- is considered as a file.
git checkout -- <file_name>
MERGE BRANCH Merge code from a branch to current working branch.
IMPORTANT: Merging is also considered as a new commit.
merge <branch_name>
TAGGING Tagging a commit is similar to bookmarking and basically, used to manage application versions.
Show all tags in alphabetical order.
git tag
Search tag with pattern; -l OR --list option.
git tag -l <pattern>
git tag -l "v1.1*"
Show tag details.
git show <tag_name>

#Create LIGHTWEIGHT TAGS.
A lightweight tag is very much like a branch that does not change, it is just a pointer to a specific commit.
git tag <tag_name>
git tag v1.1.0

#Create ANNOTATED TAGS (recommended).
Annotated tags are stored as full objects in the GIT database, checksummed, with tagger details.
Also, can be signed and verified with GNU Privacy Guard (GPG).
git tag -a <tag_name> -m <message>
git tag -a v1.1.0 -m "App version 1.1.0."

#TAGGING LATER
git tag -a <tag_name> <commit_id>
git tag -a v1.0.0 9fceb02

#SHARING TAGS; you have to explicitly push tags.
Push specific tag.
git push <remote_name> <tag_name>
git push origin v1.0.0
Push a tag with name conflicting with a branch name
git push <remote_name> tag <tag_name>
Push all tags.
git push <remote_name> --tags
git push origin --tags

#DELETE TAGS
Delete local tag.
git tag -d <tag_name>
Explicitly delete tag from remote.
git push <remote_name> :refs/tags/<tag_name>

#CHECKING OUT TAGS
This puts your repository in 'Detached HEAD' state.
git checkout <tag_name>
Detached HEAD; imagine it as a temporary branch without a name. So, instead of having a named branch reference, we only have HEAD.
If you make changes and then create a commit, that will update HEAD and tag will stay the same. And your new commit will NOT belong to any branch and will be unreachable, except by the exact commit hash.
Thus, if you need to make changes, say you are fixing a bug on an older version, for instance, then you will generally want to create a branch:
git checkout -b <new_branch> <tag_name>
PATCH #CREATE PATCH.
Create a patch with git diff. See GIT DIFF for more options.
git diff > <patch_file>
Create drupal.patch file as a patch.
git diff > drupal.patch

#Create patch for untracked/new files.
Stage first and use --cache option to create patch.
git add <new_file>
git diff --cached > drupal.patch

Futher, add --binary option to add binary files(png, mp3 etc.) to the patch.
git diff --cached --binary > drupal.patch

Create patch relative to a directory (patch will contain file details relative to this directory).
cd path/to/directory
git diff --relative > drupal.patch

#Create commit-wise patch (Only includes committed changes).
git format-patch <from_commit_id> --stdout > <patch_file>
git format-patch <from_commit_id> <to_commit_id> --stdout > <patch_file>
git format-patch f655d15 727ecaa --stdout > drupal.patch

#APPLY PATCH (Not Recommended)
git apply drupal.patch
Use -v option for verbose mode.
git apply -v drupal.patch

#APPLY PATCH (Recommended)
At first, check all changes within the patch.
git apply --stat drupal.patch
Secondly, test the patch if it is clean, and would not trouble before you apply.
git apply -v --check drupal.patch
At last, apply the patch with user signoff.
This signoff will add additional line to commit message when you 'git log'.
Example, Signed-off-by: Your Name <your@email.com>
git am --signoff drupal.patch

#REVERT PATCH
git apply -R drupal.patch

#APPLY PATCH (cURL).
Apply patch directly from URL.
curl <patch_url> | git apply
Revert above patch.
curl <patch_url> | git apply -R

NOTE:
While applying patches, if you are NOT at the correct directory path, then it will skip applying the patch.
CONFLICT Ending up with merge conflict is real pain.
To proceed further, you have to open each conflict files, and resolve the conflict, and lastly commit the accepted changes.

File with merge-conflict will end up with added code in below pattern.
<<<<<< HEAD
Current text Line-1
Current text Line-2

Current text Line-n
======
Incoming text Line-1
Incoming text Line-2
>>>>>> 82e7c0bbf3726fb2f134e123450fb837bd6f16fa

What code to keep and what to remove?
Understand first, that code between line '<<<<<< HEAD' and '======' are your current changes.
And code between line '======' and '>>>>>> 82e7c0b' are incoming changes from commit-id 82e7c0b.


How to resolve merge conflict?
Do 'git status' and find all merge-conflict files under 'Unmerged paths' details.
Now, open each file one by one and resolve conflicts using below step.


Step 1. (In our case)
- If you want to keep your CURRENT changes,
then remove all lines between '======' and '>>>>>> 82e7c0b'
- If you want to keep INCOMING changes,
then remove all lines between '<<<<<< HEAD' and '======'
Step 2.
Remove specific 3 lines '<<<<<< HEAD', '======' and '>>>>>> 82e7c0b'.
Step 3.
Save file.

If you have resolved conflicts from all the files.
Do 'git status' you will find message 'All conflicts fixed but you are still merging.'


Step 4.
Stage all resolved files with 'git add'.
Step 5.
Finally, commit the accepted changes.

NOTE:
There can be multiple conflicts within a single file.
Also, it is preferred to use IDE for resolving conflicts.
HEAD HEAD is a reference (variable) to the latest commit in the currently checked-out branch.
When you switch branches with git checkout, the HEAD revision changes to point to the tip of the new branch.


Check where HEAD points to?
cat .git/HEAD

For DETACHED HEAD, see TAGGING section.
TRAVERSE COMMITS (with HEAD) Example commit details.
* 727ecaa (HEAD -> master) Commit-5th on master.
* 0321e55 Merged branch 'branch1' to 'master'
|\
| * 87e0e48 (branch1) Commit-3rd on branch1.
| * bf6f1c0 Commit-2nd on branch1.
| * e40d985 Commit-1st on branch1.
* | 4ffd6c6 Commit-4th on master.
|/
* c64d3aa Commit-3rd on master.
* f655d15 Commit-2nd on master.
* a4e8c36 Commit-1st on master.

Traverse commits backward with ~(tilde) option (branch-specific).
Check HEAD commit details.
// Output: 727ecaa (HEAD -> master) Commit-5th on master.

git show --oneline HEAD
Travese one commit back.
// Output: 0321e55 Merged branch 'branch1' to 'master'.

git show --oneline HEAD~
git show --oneline HEAD~1
git show --oneline 727ecaa~1
Travese two commits back.
// Output: 4ffd6c6 Commit-4th on master.

git show --oneline HEAD~2
git show --oneline 727ecaa~2

Identify respective branch at merge-location with ^(caret) option, and traverse commits.
Where the two branches were merged, has two parents, one on master and one on the branch.
^1 and ^2 identifies first-branch(master[merged to]) and second-branch(branch1[merged]) respectively.


#How ^(caret) option works?
^ identifies branch (generally) at merged-location based on identifier number passed, and will point to very first commit of that branch.

Identiying the first-branch with HEAD^1.
// Output: 0321e55 Merged branch 'branch1' to 'master'.

git show --oneline HEAD^
git show --oneline HEAD^1
git show --oneline 727ecaa^1

Identiying the second-branch with HEAD^2.
Since, 727ecaa is not a merge-location to identify second-branch, hence, below commands will fail.

git show --oneline HEAD^2
git show --oneline 727ecaa^2
Instead, at commit 0321e55 (merge location) second-branch could be identified.
// Output: 87e0e48 (branch1) Commit-3rd on branch1.

git show --oneline 0321e55^2

Both ~ and ^ can be used together for commit traversing.
From HEAD identifiy first-branch and traverse one commit before.
// Output: 4ffd6c6 Commit-4th on master.

git show --oneline HEAD^1~1
From HEAD identifiy first-branch and traverse two commits before.
// Output: c64d3aa Commit-3rd on master.

git show --oneline HEAD^1~2

#REVERSE ALSO WORKS:
From HEAD traverse one commit before and identifiy first-branch.
// Output: 4ffd6c6 Commit-4th on master.

git show --oneline HEAD~1^1
From HEAD traverse one commit before and identifiy second-branch.
// Output: 87e0e48 (branch1) Commit-3rd on branch1.

git show --oneline HEAD~1^2


NOTE:
HEAD~ and HEAD^ is equivalent to HEAD~1 and HEAD^1 respectively.
HELP Show help; help OR --help.
git help

#GIT COMMANDS.
Shows all git-commands.
git help -a
Read about specific command in browser.
git help <command>
git help add
Read usage of specific command on terminal itself.
git <command> -h
git add -h

#GIT CONCEPT GUIDES.
Shows all available git concept guides.
git help -g
Read about specific concept in browser.
git help <concept>
GIT kick-start guide.
git help tutorial
GIT work and changes guide.
git help everyday
GIT history and state guide.
git help revisions
GIT collaboration guide. git help workflows
GIT IGNORE GIT will IGNORE TRACKING files/folders mentioned in .gitignore file.
Find .gitignore file in root folder or create one of your own, and mention file-names in your .gitignore file separated with a new line.


#IGNORE FROM CURRENT DIRECTORY.
Only ignore the README.txt file in the current directory, not subdir/README.txt.

/file
/README.txt

#IGNORE FROM ALL DIRECTORIES.
Ignore all files with .txt extention.

file
*.txt
But do track drupal.txt, though ignored all .txt files above.
!drupal.txt
Ignore all files in any directory named cache.
cache/
Ignore all .txt files within notes/ directory, but not from its subdirectories (notes/drupal/readme.txt will not get ignored).
notes/*.txt
Ignore all .txt files within notes/ directory and any of its subdirectories.
notes/**/*.txt

#IGNORE PARENT-DIRECTORY BUT NOT SUB-DIRECTORY.
# Ignore directory 'web' (within current directory), excluding web/modules/custom.

# (1) First, DO NOT ignore web directory
!/web
# (2) Ignore all items of web directory
/web/*
# (3) DO NOT ignore web/modules directory
!/web/modules
# (4) Ignore all items of web/modules directory
/web/modules/*
# (5) DO NOT ignore web/modules/custom directory
!/web/modules/custom

Verify .gitignore or check ignored files
git status --ignored

Read more about .gitignore.
git help ignore

NOTE:
It is possible to have additional .gitignore files in subdirectories and ignoring .gitignore file itself is also possible.
Also, if you have ignored a file, then 'git add .' will not include ignored files. Cheers!
#Search occurance of specific string in all files.
Result shows details at per file level with line number; -n or --line-number.
git grep -n "Search occurance of my_string per file."
#Result shows occurance count per file; -c or --count.
git grep -c "Count occurance of my_string per file."
REMOVE FILES git rm <file_name> = rm <file_name> + git add <file_name>.
git rm <file_name>
Removes all .log files within log/ directory.
git rm log/\*.log

Remove accidently staged files, but keep changes in working directory.
Useful if you forgot to add something to your .gitignore.

git rm --cached README

NOTE:
'git rm' does not work with UNTRACKED/NEW file.
RENAME Rename file; Example, rename README.MD file to README.TXT.
git mv <file_name> <file_newname> = mv <file_name> <file_newname> + git rm <file_name> + git add <file_newname>.

git mv <file_name> <file_newname>
git mv README.MD README.TXT
UNDOING THINGS #UNDO-MODIFICATION.
Unmodifying a modified file.
git checkout -- <file_name>

#UNDO-STAGE.
Unstage files, but keep changes in working directory.
git reset HEAD <file_name>
Unstage files, and DO NOT keep changes in working directory.
git reset --hard HEAD <file_name>

#UNDO-COMMIT.
Remove the very first commit of the repository.
git update-ref -d HEAD
Reset to a commit, but keep changes in working directory.
git reset <commit_id>
Reset to a commit, and DO NOT keep changes in working directory.
git reset --hard <commit_id>
This will leave commits after <commit_id> unreachable.

Accidentally committed with incorrect identity (user.name/user.email)?
git config --edit [OR]
git config --global --edit
This will open the editor letting you update name & email, once done execute below command:
git commit --amend --reset-author

Undo commit using revert.
Revert will create a new commit, highlighting revert details.

git revert <commit_id>
Git revert HEAD

Further, git log for revert will show:
commit cb0a734b217150b0bab0615038b6192db2e4ac71 (HEAD -> master)
Author: drupaldrug
Date: Thu Jun 18 22:38:15 2020 +0530
    Revert commit message.
    This reverts commit ce01158390af2abc5502cc1a0da3bb5710d3e561.
commit ce01158390af2abc5502cc1a0da3bb5710d3e561
Author: drupaldrug
Date: Thu Jun 18 22:35:16 2020 +0530
    My commit message.

#UNDO UNDO-COMMIT.
For this knowledge of HEAD commit-id '727ecaa' is required; Check commits:
git log --oneline
727ecaa (HEAD -> master) Commit-3rd on master.
f655d15 Commit-2nd on master.
a4e8c36 Commit-1st on master.
Now, accidently you have reset to a commit 'f655d15 Commit-2nd on master.'.
git reset f655d15
Check reset status.
git log --oneline
f655d15 (HEAD -> master) Commit-2nd on master.
a4e8c36 Commit-1st on master.
Now, UNDO it, merging with unreachable commit '727ecaa Commit-3rd on master.' will bring the situation back.
git merge 727ecaa
Check UNDO status.
git log --oneline
727ecaa (HEAD -> master) Commit-3rd on master.
f655d15 Commit-2nd on master.
a4e8c36 Commit-1st on master.
NOTE:
A commit will always exists (though unreachable), if you know the commit-id you can re-collect the commit data.
TROUBLESHOOT & OTHER Check GIT version.
git --version
Clean the screen.
clear
Shows status in graphical user interface.
git gui
GIT repository browser.
git gitk
Who changed what and when?
git blame <file_name>
BOOKS // Download Books.
Download Pro Git E-Book
GITHUB // Check status of github itself.
Check Github Status

Comments

  1. Command line instructions
    You can also upload existing files from your computer using the instructions below.


    Git global setup
    git config --global user.name "<name>"
    git config --global user.email "<email>"

    Create a new repository
    git clone <repository_url>
    cd <project>
    touch README.md
    git add README.md
    git commit -m "add README"
    git push -u origin master

    Push an existing folder
    cd existing_folder
    git init
    git remote add origin <repository_url>
    git add .
    git commit -m "Initial commit"
    git push -u origin master

    Push an existing Git repository
    cd existing_repo
    git remote rename origin old-origin
    git remote add origin <repository_url>
    git push -u origin --all
    git push -u origin --tags

    ReplyDelete
  2. STASH
    Stashing takes your modified tracked files and staged changes — and saves it on a stack of unfinished changes that you can reapply at any time (even on a different branch).

    // Stash current changes.
    git stash
    // List all stash.
    git stash list

    // Pop latest/top stash and apply.
    git stash apply
    // Pop particular stash and apply.
    git stash apply n

    // Show stash summary all/particular
    git stash show
    git stash show stash@{n}
    // Show stash patch format all/particular
    git stash show -p
    git stash show -p stash@{n}

    // Delete latest/top stash.
    git stash drop stash@{0}
    // Delete particular stash.
    git stash drop stash@{0}

    ReplyDelete
  3. Multiple SSH keys:

    ➜ ssh-keygen -t rsa -b 4096 -C "youremail@yourdomain.com"
    Generating public/private rsa key pair.
    Enter file in which to save the key (/Users/dev/.ssh/id_rsa): /Users/dev/.ssh/id_rsa_yoyo
    Enter passphrase (empty for no passphrase):
    Enter same passphrase again:
    Your identification has been saved in /Users/dev/.ssh/id_rsa_yoyo.
    Your public key has been saved in /Users/dev/.ssh/id_rsa_yoyo.pub.
    The key fingerprint is:
    SHA256:/fdsdsdga4EITXUc/K5nRyUfdsferfrefdfdst4jtzkeAI youremail@yourdomain.com
    The key's randomart image is:
    +---[RSA 4096]----+
    | .+. o+|
    | . .+ +o|
    | .. . B o|
    | E . O. .o = |
    | o S *.o o.*|
    | = O +...++|
    | o . o....|
    | .=..o|
    | +o .*|
    +----[SHA256]-----+

    Now use your yoyo public key to upload to git agent
    ➜ cat ~/.ssh/id_rsa_yoyo.pub

    // Create config for .ssh for mapping repositories
    ➜ vim ~/.ssh/config

    #yoyo account
    Host github.com-yoyo
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_yoyo

    // Now come back to project

    ➜ cd myproject
    ➜ git init
    Initialized empty Git repository in /myproject/.git/



    // Generally we have repository as git@github.com:yoyo/yoyo_proj.git
    // But since we are mapping it with ~/.ssh/config, remote should look somewhat like
    // git@github.com-<specific_account>:yoyo/yoyo_proj.git
    ➜ git remote add origin git@github.com-yoyo:yoyo/yoyo_proj.git
    ➜ git remote -v
    origin git@github.com-yoyo:yoyo/yoyo_proj.git (fetch)
    origin git@github.com-yoyo:yoyo/yoyo_proj.git (push)

    // Now u can collaborate
    ➜ git pull origin develop

    ReplyDelete
    Replies
    1. https://gist.github.com/jexchan/2351996

      Delete
    2. https://superuser.com/a/1473365

      Delete
  4. Toggle branch checkout, use hyphen
    git checkout -

    ReplyDelete
  5. If wrongly pulled code and facing conflict issues
    git merge --abort
    Similarly,
    git rebase --abort

    ReplyDelete
  6. git show commit_id
    show changes in the commit

    ReplyDelete
  7. Pull branch from different repository
    git remote add another_repo another_repo_fork_link
    git fetch another_repo
    git checkout -b my-branch
    git pull another_repo branch

    ReplyDelete
    Replies
    1. git fetch another_repo branch_name
      git checkout branch_name

      Also works

      Delete
    2. git fetch remote rbranch:lbranch
      git checkout lbranch

      ...where rbranch is the remote branch or source ref and lbranch is the as yet non-existent local branch or destination ref you want to track and which you probably want to name the same as the remote branch or source ref. This is explained under options in the explanation of .

      Delete
    3. Checking out pull requests locally "git fetch origin pull/ID/head:BRANCH_NAME"

      https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/reviewing-changes-in-pull-requests/checking-out-pull-requests-locally

      Delete
  8. Cherry picking is to choose a commit from one branch and apply it to another
    git checkout my_branch
    git cherry-pick commit_hash_from_other_branch
    [merge conflicts if any]
    [git cherry-pick --continue]

    ReplyDelete
  9. Show commited files
    git show --pretty="" --name-only 81ecf27095e2ddf3

    ReplyDelete
  10. syntax error near unexpected token `('

    If a file has special characters put them in quotes
    git add "myfile(x86).yml"

    ReplyDelete
  11. Convert your remote repository to bare repository

    Execute the following command in your remote repository folder

    git config --bool core.bare true

    ReplyDelete
  12. git diff accepts an optional exclude

    git diff -- ":(exclude)thingToExclude"
    You might want to add some wild cards
    git diff -- ":(exclude)*/thingToExclude/*"
    Target specific file types
    git diff -- ":(exclude)*/$1/*.png"

    https://stackoverflow.com/a/57892848

    ReplyDelete
  13. IMPORTANT: Updates that commit ID; consequently if any tag will be cleared, though will exists.
    git commit --amend --reset-author
    OR
    git commit --amend --author="myuser <mymail@drupal.org>"

    ReplyDelete
  14. How GIT handles symlinks:

    ➜ git ls-files -s docroot/simplesaml
    120000 fd1b2965bc501ee3bbd680c2a8ce07b5e24551d3 0 docroot/mysymlink
    ➜ git cat-file -p fd1b2965bc501ee3bbd680c2a8ce07b5e24551d3
    ../vendor/simplesamlphp/simplesamlphp/www/%

    Also check in file : .git/objects/fd/1b2965bc501ee3bbd680c2a8ce07b5e24551d3

    More details: https://stackoverflow.com/a/18791647

    ReplyDelete
  15. Rename branch
    If you want to rename a branch while pointed to any branch, do:
    git branch -m
    If you want to rename the current branch, you can do:
    git branch -m

    https://stackoverflow.com/a/6591218

    ReplyDelete
  16. # Debug git command if over SSH.
    # Debug level 1, 2 or 3 with -v, -vv or -vvv.
    GIT_SSH_COMMAND="ssh -v" git push origin my-branch

    ReplyDelete
    Replies
    1. https://stackoverflow.com/a/35017258

      Delete
    2. https://askubuntu.com/a/620985

      Delete
  17. In case, connection to github is lost due to git hook taking more time to execute.
    "Connection to github.com closed by remote host."

    Adding following settings in .ssh\config would send a null packet to the server every 60 seconds (keeping the connection alive) for 30 rounds. This would buy you 30 minutes of connection.

    Host *
    ServerAliveInterval 60
    ServerAliveCountMax 30

    https://stackoverflow.com/a/65818657

    ReplyDelete
  18. A successful Git branching model https://nvie.com/posts/a-successful-git-branching-model/

    ReplyDelete
  19. Reference- https://microsoft.github.io/code-with-engineering-playbook/source-control/git-guidance/

    ReplyDelete
  20. Git commands- https://confluence.atlassian.com/bitbucketserver/basic-git-commands-776639767.html

    ReplyDelete
  21. Git was built in 5 days - https://graphite.dev/blog/understanding-git

    ReplyDelete
  22. Inside .git - https://jvns.ca/blog/2024/01/26/inside-git/

    ReplyDelete

Post a Comment

Drupal Contribution
Git Commands
RESTful Services
Lando Commands
Docker Commands
MySQL
Database Quick Code
Drush Commands
Drupal Console
PHP Quick Code
Drupal Quick Code
Composer Commands
Linux Commands
Linux Shell Scripting
Drupal Hooks
Twig Tricks
PHPUnit Test
PhpMyAdmin
Drupal Constants
CSS Clues
BLT Commands
Vagrant Commands
Localhost
127.0.0.1
Drupal Interview
Drupal Certifications
Concept & Definitions
Mac Tips
Windows Tips
Browser Tips

Best Practice

Use 'elseif' instead of 'else if'
#CodingTips

As of PHP 5.4 you can also use the short array syntax, which replaces array() with []
#CodingTips

Functions in general shall be named using snake_case(say, my_function()), and using camelCase(say, myFunction()) when declared within a plugin class
#CodingTips

Variables in general shall be named using snake_case(say, $my_variable), and using camelCase(say, $myVariable) when declared within a plugin class
#CodingTips

Manage automatically assigning of new permissions whenever a module is enabled here- admin/config/people/accounts
#ConfigurationTips

Manage source of Main-menu and User-menu links here- admin/structure/menu/settings
#ConfigurationTips

Helper function(s) shall be named prefixing an underscore(say, _my_helper_function()), which can prevent hooks from being called
#CodingTips

Ideally, configuring of 'Private file system path' at admin/config/media/file-system should be located outside of your Drupal root folder(say, ../my_private_files)
#ConfigurationTips

You should be aware that uploading files as 'Private file' will slow down the process of loading the files as Drupal has to be bootstrapped for every file that needs to be downloaded
#ConfigurationTips #BeAware

Code should always be pushed up(dev -> staging -> production) and databases should only be pushed down(production -> staging -> dev)
#DevelopmentTips

Get Raw SQL Query of drupal dynamic queries before executing it using $query->__toString();
#DebugTips

In VI-Editor, Press ESC key to come in command mode and for undo type :U and for redo type :Ctrl+R
#LinuxTips

Insert queries must always use a query builder object(layer of abstraction), allowing individual database drivers special handling for column values (if applicable), example case for LOB and BLOB fields.
#DatabaseQueryTips

Drupal uses the .inc extension to prevent files from being executed directly.
#DevelopmentTips

Popular Posts