🖥️git
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the git command with important options and switches using examples.
25 minute read
▁ ▂ ▃ ▄ ꧁ 🔴☠ COMMANDLINE-KUNGFU WITH CHEATSHEETS ☠🔴꧂▅ ▃ ▂ ▁
# ██████╗ ██╗████████╗
# ██╔════╝ ██║╚══██╔══╝
# ██║ ███╗██║ ██║
# ██║ ██║██║ ██║
# ╚██████╔╝██║ ██║
# ╚═════╝ ╚═╝ ╚═╝
add, commit, push, and pull.
# Bare minimum git for personal use
git diff --name-only HEAD | cpio -o -Hnewc --quiet | ssh HOST '(cd REPO_DIR && cpio -iduv --quiet -Hnewc)'
# Copy uncommitted changes to remote git repository Copy changed files from the remote git repository, _including binary ones_, staged and unstaged alike. Note that this command doesn't handle deleted files properly. The reverse of the excellent command
gitdir="/var/git";find $gitdir -name ".git" 2> /dev/null | sed 's/\/.git/\//g' | awk '{print "\033[1;32m\nRepo ----> \033[0m " $1; system("git --git-dir="$1".git --work-tree="$1" status")}'
# List status of your git repos and let us know if there is any new files to commit. Source: http://www.bashoneliners.com/oneliners/oneliner/225/ This is sample output
Repo ----> /var/git/router/TG799VAC-XTREME-17.2-MINT/
On branch master
Your branch is up to date with 'origin/master'.
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: README.md
Changes not staged for commit:
(use "git add/rm <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
deleted: test.sh
# To set your identity:
git config --global user.name "John Doe"
git config --global user.email [email protected]
# To set your editor:
git config --global core.editor emacs
# To enable color:
git config --global color.ui true
# To stage all changes for commit:
git add --all
# To stash changes locally, this will keep the changes in a separate changelist
# called stash and the working directory is cleaned. You can apply changes
# from the stash anytime
git stash
# To stash changes with a message
git stash save "message"
# To list all the stashed changes
git stash list
# To apply the most recent change and remove the stash from the stash list
git stash pop
# To apply any stash from the list of stashes. This does not remove the stash
# from the stash list
git stash apply stash@{6}
# To commit staged changes
git commit -m "Your commit message"
# To edit previous commit message
git commit --amend
# Git commit in the past
git commit --date="`date --date='2 day ago'`"
git commit --date="Jun 13 18:30:25 IST 2015"
# more recent versions of Git also support --date="2 days ago" directly
# To change the date of an existing commit
git filter-branch --env-filter \
'if [ $GIT_COMMIT = 119f9ecf58069b265ab22f1f97d2b648faf932e0 ]
then
export GIT_AUTHOR_DATE="Fri Jan 2 21:38:53 2009 -0800"
export GIT_COMMITTER_DATE="Sat May 19 01:01:01 2007 -0700"
fi'
# To removed staged and working directory changes
git reset --hard
# To go 2 commits back
git reset --hard HEAD~2
# To remove untracked files
git clean -f -d
# To remove untracked and ignored files
git clean -f -d -x
# To push to the tracked master branch:
git push origin master
# To push to a specified repository:
git push [email protected]:username/project.git
# To delete the branch "branch_name"
git branch -D branch_name
# To make an exisiting branch track a remote branch
git branch -u upstream/foo
# To see who commited which line in a file
git blame filename
# To sync a fork with the master repo:
git remote add upstream [email protected]:name/repo.git # Set a new repo
git remote -v # Confirm new remote repo
git fetch upstream # Get branches
git branch -va # List local - remote branches
git checkout master # Checkout local master branch
git checkout -b new_branch # Create and checkout a new branch
git merge upstream/master # Merge remote into local repo
git show 83fb499 # Show what a commit did.
git show 83fb499:path/fo/file.ext # Shows the file as it appeared at 83fb499.
git diff branch_1 branch_2 # Check difference between branches
git log # Show all the commits
git status # Show the changes from last commit
# Commit history of a set of files
git log --pretty=email --patch-with-stat --reverse --full-index -- Admin\*.py > Sripts.patch
# Import commits from another repo
git --git-dir=../some_other_repo/.git format-patch -k -1 --stdout <commit SHA> | git am -3 -k
# View commits that will be pushed
git log @{u}..
# View changes that are new on a feature branch
git log -p feature --not master
git diff master...feature
# Interactive rebase for the last 7 commits
git rebase -i @~7
# Diff files WITHOUT considering them a part of git
# This can be used to diff files that are not in a git repo!
git diff --no-index path/to/file/A path/to/file/B
# To pull changes while overwriting any local commits
git fetch --all
git reset --hard origin/master
# Update all your submodules
git submodule update --init --recursive
# Perform a shallow clone to only get latest commits
# (helps save data when cloning large repos)
git clone --depth 1 <remote-url>
# To unshallow a clone
git pull --unshallow
# Create a bare branch (one that has no commits on it)
git checkout --orphan branch_name
# Checkout a new branch from a different starting point
git checkout -b master upstream/master
# Remove all stale branches (ones that have been deleted on remote)
# So if you have a lot of useless branches, delete them on Github and then run this
git remote prune origin
# The following can be used to prune all remotes at once
git remote prune $(git remote | tr '\n' ' ')
# Revisions can also be identified with :/text
# So, this will show the first commit that has "cool" in their message body
git show :/cool
# Undo parts of last commit in a specific file
git checkout -p HEAD^ -- /path/to/file
# Revert a commit and keep the history of the reverted change as a separate revert commit
git revert <commit SHA>
# Pich a commit from a branch to current branch. This is different than merge as
# this just applies a single commit from a branch to current branch
git cherry-pick <commit SHA1>
# Undo last commit
# If you want to nuke commit C and never see it again
# (F)
# A-B-C
# ↑
# master
git reset --hard HEAD~1
# Undo last commit
# If you want to undo the commit but keep your changes
# (F)
# A-B-C
# ↑
# master
git reset HEAD~1
# list files changed in ${commit_id}
git diff-tree --no-commit-id --name-only -r ${commit_id}
# list files changed in ${commit_id}, porcelain way, meant to be user facing
git show --pretty="" --name-only bd61ad98
# See everything you have done, across branches, in a glance,
# then go to the place right before you broke everything
git reflog
git reset HEAD@{hash}
# To move your most recent commit from one branch and stage it on TARGET branch
git reset HEAD~ --soft
git stash
git checkout TARGET
git stash pop
git add .
#==============================#
# CMD GIT Versionsverwaltung
#==============================##==============================#
git log --author=$USER --format="- %B" --since=-7days --reverse |mail -s "What I've done this week" boss@company\.com
git log --date=short --format="%ci"|awk '{print $1}'|uniq
# Which days I've worked...
git log --merges | grep ^Date | awk '{ print $2 }' | sort | uniq -c | sort -n
# Number of git merges by day of the week.
git config --global core.editor "gvim --nofork"
# to use gvim to edit your git messages set gits core editor as follows
git -s
# For more succinct output from git status, add the -s option.
git commit -a -m 'commit message'
# Using git, add and commit all modified files in one command
git ls-tree -r --name-only HEAD | tr A-Z a-z | sort | uniq -d
# List files that confuse Git on Windows by differing only by case
git push --set-upstream origin master
# Pushing changes to an empty git repository for the first time After cloning an empty repository on the client ("git clone" just after "git init", for instance), "git push" fails. In order to be able to push to this repository for the first time, you need to run the above command. It will link your local "master" branch to the "master" branch in the origin server, and push the changes. This is only necessary only for the first push; after that, you can use just the commands "git push" or "git pull" in order to do this operations.
(find . -name \*.git 2>/dev/null|grep -oP '^(.*)(?=\/\.git$)'|while read l;do pushd "$l";git status;popd;printf "\n";done)
# find git
# Repostitory anlegen
# -------------------
cd /home/git
mkdir <Zielverzeichnis>
cp -r <Quelle> <Zielverzeichnis>
cd <Zielverzeichnis>
git init
git config --global user.name "Tux Git"
git config --global user.email "[email protected]"
# alle Dateien im aktuellen Verzeichnis und Unterverzeichnis hinzufügen
git add .
git commit -am "Postfix Konfiguration MX4"
# Repository anschauen
# --------------------
git status
# zeigt commits an (--oneline optional)
git log --oneline
# zeigt auch alte commits an
git reflog
# diffs anschauen
git show -1
# diff zwischen jetzt und zwei Commits zurück
git diff HEAD~2 HEAD main.cf
# Aenderung committen
# -------------------
cd /home/git/<Zielverzeichnis>
cp <Quelldatei> <Zielverzeichnis>
# geaenderten Status anzeigen
git status
git commit -am "Update main.cf"
# Log anschauen
git log --oneline
# alte Version auschecken
# ------------------------
git checkout <gehashte Version>
# Dateien liegen jetzt im alter Version vor ->git status
# optional wieder auf alten Head zurückgehen mit
# git reflog
# git reset --hard <gehashte Version>
# git status zeigt jetzt "HEAD losgelöst"
# git checkout master
# git status -> steht auf master
git show $COMMIT
# OR
git diff HEAD^ HEAD
# Diff Against the Previous Commits
git diff --ignore-space-change myFile.txt
# How to git diff a file version excluding space differences - This git command allows to get differences on local modified file ignoring space or blanks as changes
git init
git remote add origin PATH/TO/REPO
git fetch
git reset --hard origin/master
# Git Clone into non empty directory
Using Git
===============
Global Settings
-----------
Related Setup: https://gist.github.com/hofmannsven/6814278
Related Pro Tips: https://ochronus.com/git-tips-from-the-trenches/
Interactive Beginners Tutorial: http://try.github.io/
Reminder
-----------
Press `minus + shift + s` and `return` to chop/fold long lines!
Show folder content: `ls -la`
Notes
-----------
Do not put (external) dependencies in version control!
Setup
-----------
See where Git is located:
`which git`
Get the version of Git:
`git --version`
Create an alias (shortcut) for `git status`:
`git config --global alias.st status`
Help
-----------
Help:
`git help`
General
-----------
Initialize Git:
`git init`
Get everything ready to commit:
`git add .`
Get custom file ready to commit:
`git add index.html`
Commit changes:
`git commit -m "Message"`
Add and commit in one step:
`git commit -am "Message"`
Remove files from Git:
`git rm index.html`
Update all changes:
`git add -u`
Remove file but do not track anymore:
`git rm --cached index.html`
Move or rename files:
`git mv index.html dir/index_new.html`
Undo modifications (restore files from latest commited version):
`git checkout -- index.html`
Restore file from a custom commit (in current branch):
`git checkout 6eb715d -- index.html`
Reset
-----------
Go back to commit:
`git revert 073791e7dd71b90daa853b2c5acc2c925f02dbc6`
Soft reset (move HEAD only; neither staging nor working dir is changed):
`git reset --soft 073791e7dd71b90daa853b2c5acc2c925f02dbc6`
Undo latest commit: `git reset --soft HEAD~ `
Mixed reset (move HEAD and change staging to match repo; does not affect working dir):
`git reset --mixed 073791e7dd71b90daa853b2c5acc2c925f02dbc6`
Hard reset (move HEAD and change staging dir and working dir to match repo):
`git reset --hard 073791e7dd71b90daa853b2c5acc2c925f02dbc6`
Update & Delete
-----------
Test-Delete untracked files:
`git clean -n`
Delete untracked files (not staging):
`git clean -f`
Unstage (undo adds):
`git reset HEAD index.html`
Commit to most recent commit:
`git commit --amend -m "Message"`
Update most recent commit message:
`git commit --amend -m "New Message"`
Branch
-----------
Show branches:
`git branch`
Create branch:
`git branch branchname`
Change to branch:
`git checkout branchname`
Create and change to new branch:
`git checkout -b branchname`
Rename branch:
`git branch -m branchname new_branchname` or:
`git branch --move branchname new_branchname`
Show all completely merged branches with current branch:
`git branch --merged`
Delete merged branch (only possible if not HEAD):
`git branch -d branchname` or:
`git branch --delete branchname`
Delete not merged branch:
`git branch -D branch_to_delete`
Merge
-----------
True merge (fast forward):
`git merge branchname`
Merge to master (only if fast forward):
`git merge --ff-only branchname`
Merge to master (force a new commit):
`git merge --no-ff branchname`
Stop merge (in case of conflicts):
`git merge --abort`
Stop merge (in case of conflicts):
`git reset --merge` // prior to v1.7.4
Merge only one specific commit:
`git cherry-pick 073791e7`
Stash
-----------
Put in stash:
`git stash save "Message"`
Show stash:
`git stash list`
Show stash stats:
`git stash show stash@{0}`
Show stash changes:
`git stash show -p stash@{0}`
Use custom stash item and drop it:
`git stash pop stash@{0}`
Use custom stash item and do not drop it:
`git stash apply stash@{0}`
Delete custom stash item:
`git stash drop stash@{0}`
Delete complete stash:
`git stash clear`
Gitignore & Gitkeep
-----------
About: https://help.github.com/articles/ignoring-files
Useful templates: https://github.com/github/gitignore
Add or edit gitignore:
`nano .gitignore`
Track empty dir:
`touch dir/.gitkeep`
Log
-----------
Show commits:
`git log`
Show oneline-summary of commits:
`git log --oneline`
Show oneline-summary of commits with full SHA-1:
`git log --format=oneline`
Show oneline-summary of the last three commits:
`git log --oneline -3`
Show only custom commits:
`git log --author="Sven"`
`git log --grep="Message"`
`git log --until=2013-01-01`
`git log --since=2013-01-01`
Show only custom data of commit:
`git log --format=short`
`git log --format=full`
`git log --format=fuller`
`git log --format=email`
`git log --format=raw`
Show changes:
`git log -p`
Show every commit since special commit for custom file only:
`git log 6eb715d.. index.html`
Show changes of every commit since special commit for custom file only:
`git log -p 6eb715d.. index.html`
Show stats and summary of commits:
`git log --stat --summary`
Show history of commits as graph:
`git log --graph`
Show history of commits as graph-summary:
`git log --oneline --graph --all --decorate`
Compare
-----------
Compare modified files:
`git diff`
Compare modified files and highlight changes only:
`git diff --color-words index.html`
Compare modified files within the staging area:
`git diff --staged`
Compare branches:
`git diff master..branchname`
Compare branches like above:
`git diff --color-words master..branchname^`
Compare commits:
`git diff 6eb715d`
`git diff 6eb715d..HEAD`
`git diff 6eb715d..537a09f`
Compare commits of file:
`git diff 6eb715d index.html`
`git diff 6eb715d..537a09f index.html`
Compare without caring about spaces:
`git diff -b 6eb715d..HEAD` or:
`git diff --ignore-space-change 6eb715d..HEAD`
Compare without caring about all spaces:
`git diff -w 6eb715d..HEAD` or:
`git diff --ignore-all-space 6eb715d..HEAD`
Useful comparings:
`git diff --stat --summary 6eb715d..HEAD`
Blame:
`git blame -L10,+1 index.html`
Releases & Version Tags
-----------
Show all released versions:
`git tag`
Show all released versions with comments:
`git tag -l -n1`
Create release version:
`git tag v1.0.0`
Create release version with comment:
`git tag -a v1.0.0 -m 'Message'`
Checkout a specific release version:
`git checkout v1.0.0`
Collaborate
-----------
Show remote:
`git remote`
Show remote details:
`git remote -v`
Add remote origin from GitHub project:
`git remote add origin https://github.com/user/project.git`
Add remote origin from existing empty project on server:
`git remote add origin ssh://[email protected]/path/to/repository/.git`
Remove origin:
`git remote rm origin`
Show remote branches:
`git branch -r`
Show all branches:
`git branch -a`
Compare:
`git diff origin/master..master`
Push (set default with `-u`):
`git push -u origin master`
Push to default:
`git push origin master`
Fetch:
`git fetch origin`
Fetch a custom branch:
`git fetch origin branchname:local_branchname`
Pull:
`git pull`
Pull specific branch:
`git pull origin branchname`
Merge fetched commits:
`git merge origin/master`
Clone to localhost:
`git clone https://github.com/user/project.git` or:
`git clone ssh://[email protected]/~/dir/.git`
Clone to localhost folder:
`git clone https://github.com/user/project.git ~/dir/folder`
Clone specific branch to localhost:
`git clone -b branchname https://github.com/user/project.git`
Delete remote branch (push nothing):
`git push origin :branchname` or:
`git push origin --delete branchname`
Archive
-----------
Create a zip-archive: `git archive --format zip --output filename.zip master`
Export/write custom log to a file: `git log --author=sven --all > log.txt`
Troubleshooting
-----------
Ignore files that have already been committed to a Git repository: http://stackoverflow.com/a/1139797/1815847
Security
-----------
Hide Git on the web via `.htaccess`: `RedirectMatch 404 /\.git`
(more info here: http://stackoverflow.com/a/17916515/1815847)
Large File Storage
-----------
Website: https://git-lfs.github.com/
Install: `brew install git-lfs`
Track `*.psd` files: `git lfs track "*.psd"` (init, add, commit and push as written above)
# Delete first 10 branches from remote origin (exclude master)
git branch -a | grep "remotes/origin" | grep -v master | sed 's/^[ *]*//' | sed 's/remotes\/origin\///' | head -n10 | sed 's/^/git push origin :/' | bash
# Clone all repos from a user with lynx
# https://wuseman.github.io/wcloner/
lynx -dump -nonumbers https://github.com/USER?tab=repositories|grep '/USER/'|cut -d'/' -f1,2,3,4,5|uniq|xargs -L1 git clone
# Holt mir das remote Verzeichnis
git clone [email protected]:/home/git/linux_lxu_io
#-----------------------------------------------------------------------///
# git-usage-stats
626 status
544 commit
526 add
411 lg
253 diff
249 grep
224 checkout
207 rebase
164 push
163 show
132 stash
97 log
76 rebaselocal
58 reset
51 pull
49 b
42 mergetool
29 branch
27 stauts
27 clean
23 hgrep
20 lga
18 pull-request
18 cherry-pick
14 open
12 tag
12 rm
11 merge
11 blame
10 chkdelete
9 mv
8 whitespacecheckout
8 remote
8 lgaa
8 dif
8 browse
7 lgu
7 fetch
5 lgb
5 clone
4 l
4
3 lgd
3 lgaaa
3 g
3 diffchar
2 update
2 satus
2 revert
2 pul
2 lug
2 ls-files
2 list
2 --help
2 help
2 diffword
2 difff
1 vomm
1 staut
1 shiw
1 review
1 psh
1 phpsh
1 phps
1 mertet-y
1 ls
1 lgaaaa
1 lb
1 devel
1 dd
1 create
1 commm-a
1 commm
1 com
1 chek-p
1 chekout
1 chekc-p
1 chek-
1 adiff
1 ad
#-----------------------------------------------------------------------///
git log --author=$USER --format="- %B" --since=-7days --reverse |mail -s "What I've done this week" boss@company\.com
# Mail a report of what you've done this week to your boss.
# Export a git project to a directory
git archive master | tar x -C /path/to/dir/to/export
# Explanation: The git archive command basically creates a tar file. The one-liner is to create a directory instead, without an intermediate tar file. The tar command above will untar the output of git archive into the directory specified with the -C flag. The directory must exist before you run this command.
# List all non Git comited files and make a gzip archive with them
GITFOLDER="/srv/some/folder" ls-files --others --exclude-standard | tar czf ${GITFOLDER}-archives/uploads-$(date '+%Y%m%d%H%M').tar.gz -T -
# Explanation: Assuming your web app has a git checkout is in /srv/some/folder (i.e. there is a /srv/some/folder/.git), archive the user uploads to /srv/some/folder-archives with that one liner. Use:
cd /srv/some/folder
# this one-liner
# Limitations: A fully complete script would:
# Check if $GITFOLDER exists
# Check if $GITFOLDER has a .git directory
# Create a temporary (e.g. tmp=$(mktemp)) file to log anything; if [ "$?" -ne 0 ] ; exit with status exit 1, otherwise delete the $tmp file and exit 0.
# Count the lines of each file extension in a list of files
git ls-files | xargs wc -l | awk -F ' +|\\.|/' '{ sumlines[$NF] += $2 } END { for (ext in sumlines) print ext, sumlines[ext] }'
# Explanation: The pipeline:
# git ls-files -- produces the list of files in a Git repository. It could be anything else that produces a list of filenames, for example: find . -type f
# xargs wc -l -- run wc -l to count the lines in the filenames coming from standard input. The output is the line count and the filename
# The final awk command does the main work: extract the extension name and sum the line counts:
# -F ' +|\\.|/' -- use as field separator multiples of spaces, or a dot, or a slash
# { sumlines[$NF] += $2 } -- $NF contains the value of the last field, which is the filename extension, thanks to the dot in the field separator, and $2 contains the value of the second field in the input, which is the line count. As a result, we are building the sumlines associative array, summing up the line counts of files with the same extension
# END { for (ext in sumlines) print ext, sumlines[ext] }' -- After all lines have been processed, print the extension and the line count.
# Random Git Commit
git commit -m "$(w3m whatthecommit.com | head -n 1)"
# Explanation: This will commit a message pulled from What the Commit. -m allows you to provide the commit message without entering your editor w3m is a terminal based web browser. We basically use it to strip out all of the html tags head -n 1 will grab only the first line
# Limitations: This requires you to have w3m installed
# Test git archive before actually creating an archive // fake dry run
git archive master some/project/subdir | tar t
# Explanation: git archive does not have a --dry-run flag, and it would be nice to see what files would be in the archive before actually creating it.
# git archive master some/project/subdir
# Create an archive from the master branch, with only a specified sub-directory of the project in it (instead of the entire repo)
# Note: without specifying a file, the archive is dumped to standard output
# tar t : the t flag of tar is to list the content of an archive. In this example the content comes from standard input (piped from the previous command)
# In other words, this command creates an archive without ever saving it in a file, and uses tar t to list the contents. If the output looks good, then you can create the archive with:
git archive master -o file.tar some/project/subdir
# Scan entire Git repo for dangerous Amazon Web Service IDs
git grep -Ew '[A-Z0-9]{20}'
# Explanation:
# Letting your AWS credentials escape is very dangerous! This simple tool makes sure none of your secrets make into version control and therefore out into the hands of evil robots.
# Use Git to quickly search for things that look like AWS IDs: a 20-character uppercase word. The -w adds word boundaries around the search pattern, and the -E make it possible to use extended regex syntax, in this example the {20} count.
## Related one-liners
# Scan entire Git repos for dangerous Amazon Web Service IDs
git ls-tree --full-tree -r --name-only HEAD | xargs egrep -w '[A-Z0-9]{20}'
# Explanation: Letting your AWS credentials escape is very dangerous! This simple tool makes sure none of your secrets make into version control and therefore out into the hands of evil robots.
# Use Git to quickly list all files in the repos. Then, take this list and search for things that look like AWS IDs: a 20-character uppercase word.
# Scan entire Git repos for dangerous Amazon Web Service IDs
git ls-tree --full-tree -r --name-only HEAD | xargs egrep -w '[A-Z0-9]{20}'
# Explanation: Letting your AWS credentials escape is very dangerous! This simple tool makes sure none of your secrets make into version control and therefore out into the hands of evil robots.
# Use Git to quickly list all files in the repos. Then, take this list and search for things that look like AWS IDs: a 20-character uppercase word.
## Alternative one-liners:
# Scan entire Git repo for dangerous Amazon Web Service IDs
git grep -Ew '[A-Z0-9]{20}'
# Explanation: Letting your AWS credentials escape is very dangerous! This simple tool makes sure none of your secrets make into version control and therefore out into the hands of evil robots.
# Use Git to quickly search for things that look like AWS IDs: a 20-character uppercase word. The -w adds word boundaries around the search pattern, and the -E make it possible to use extended regex syntax, in this example the {20} count.
# Print a count of the commits per day in a git repo.
git log --pretty=format:%cd --date=short | uniq -c
# Cleanup remote repository of all branches already merged into master This is useful in teams where developers don't bother to remove branches after merging PR. These branches make it hard to seek for really useful branches, which gives us a nice value of finding and exploring other people's code even before they create PR for it.
git branch --remotes --merged | grep -v master | sed 's@ origin/@:@' | xargs git push origin
git log -p --name-only --follow <file>
# get full git commit history of single file
# rwxr-xr-x
$(cd "$(dirname "${BASH_SOURCE[0]}")" && git rev-parse --show-toplevel)
# Get the full path of a bash script's Git repository head.
# Rather than complicated and fragile paths relative to a script like "../../other", this command will retrieve the full path of the files repository head. Safe with spaces in directory names. Works within a symlinked directory. Broken down: cd "$(dirname "${BASH_SOURCE[0]}")" temporarily changes directories within this expansion. Double quoted "$(dirname" and ")" with unquoted ${BASH_SOURCE[0]} allows spaces in the path. git rev-parse --show-toplevel gets the full path of the repository head of the current working directory, which was temporarily changed by the "cd".
# Scan entire Git repo for dangerous Amazon Web Service IDs
git grep -Ew '[A-Z0-9]{20}'
# Scan entire Git repos for dangerous Amazon Web Service IDs
git ls-tree --full-tree -r --name-only HEAD | xargs egrep -w '[A-Z0-9]{20}'
# Print the list of your Git commits this month
git log --since='last month' --author="$(git config user.name)" --oneline
git config --add user.name "git User" ; git config --add user.email "gir@localhost" ; git config --add color.ui "auto"
# Rename all .markdown files in a git repository .md
for file in *markdown; do git mv $file `echo $file | cut -f1 -d'.'`.md ; done
# Pull multiple repositories in child folders (a.k.a. I'm back from leave script) [Windows]
gci -Directory | foreach {Push-Location $_.Name; git fetch --all; git checkout master; git pull; Pop-Location}
# Stage all files for commit except those that are *.config at any level within your git repo [Windows]
git status | Where-Object {$_.Contains('modified') -and !$_.Contains('.config')} | ForEach-Object { git add $_.Replace('modified:','').Trim() }
# Copy current branch to clipboard [Windows]
(git branch | Where-Object { $_.Contains('*') } | Select-Object -First 1).Trim('*').Trim() | Set-Clipboard
# Delete all local branches that are not master [Windows]
git branch | Where-Object { !$_.Contains('master') } | ForEach-Object { git branch -D $_.Trim() }
# Delete all local branches that have been merged into master [Windows]
git branch --merged origin/master | Where-Object { !$_.Contains('master') } | ForEach-Object { git branch -d $_.trim() }
# Initialise git in working directory with latest Visual Studio .gitignore [Windows]
git init; (Invoke-WebRequest https://raw.githubusercontent.com/github/gitignore/master/VisualStudio.gitignore -UseBasicParsing).Content | Out-File -FilePath .gitignore -Encoding utf8; git add -A
# Open browser from terminal to create PR after pushing something in Git in MAC
git remote -v |grep origin|tail -1|awk '{print $2}'|cut -d"@" -f2|sed 's/:/\//g'|xargs -I {} open -a "Google Chrome" https://{}
# Delete all local git branches that have been merged and deleted from remote
git branch -d $( git branch -vv | grep '\[[^:]\+: gone\]' | awk '{print $1}' | xargs )
# Print all git repos from a user (only curl and grep)
curl -s https://api.github.com/users/<username>/repos?per_page=1000 | grep -oP '(?<="git_url": ").*(?="\,)'
# Print all git repos from a user - Python is installed on many boxes (in case you could not afford installing jq).
curl -s "https://api.github.com/users/<username>/repos?per_page=1000" | python <(echo "import json,sys;v=json.load(sys.stdin);for i in v:; print(i['git_url']);" | tr ';' '\n')
# Print all git repos from a user - in case you could afford installing jq
curl -s "https://api.github.com/users/<username>/repos?per_page=1000" | jq '.[].git_url'
# Print the list of your Git commits this month
git log --since='last month' --author="$(git config user.name)" --oneline
# Print github url for the current url - Works for repos cloned via ssh or https.
git remote -v | sed -n '/github.com.*push/{s/^[^[:space:]]\+[[:space:]]\+//;s|[email protected]:|https://github.com/|;s/\.git.*//;p}'
# Sample output
# Cloned using https
#----------------------#
# $ git remote -v
# origin https://github.com/bartonski/barton-unit-circle.git (fetch)
# origin https://github.com/bartonski/barton-unit-circle.git (push)
# $ git remote -v | sed -n '/github.com.*push/{s/^[^[:space:]]\+[[:space:]]\+//;s|[email protected]:|https://github.com/|;s/
# \.git.*//;p}'
# https://github.com/bartonski/barton-unit-circle
#----------------------#
# cloned using ssh
# $ git remote -v
# origin [email protected]:bartonski/barton-unit-circle.git (fetch)
# origin [email protected]:bartonski/barton-unit-circle.git (push)
# Fri Oct 11 12:44:43 bartonc@BartonCW10L: /tmp/barton-unit-circle
# $ git remote -v | sed -n '/github.com.*push/{s/^[^[:space:]]\+[[:space:]]\+//;s|[email protected]:|https://github.com/|;s/
# \.git.*//;p}'
# https://github.com/bartonski/barton-unit-circle
# push to Github
git add -u;
git commit -m "New backup `date +'%Y-%m-%d %H:%M:%S'`";
git push origin master
## Git
# remove a repo
find . -type f | grep -i ".git" | xargs rm
cd ..
rm -rf
# sets your name and email for commit messages
git config --global user.name 'John Doe'
git config --global user.email [email protected]
# helps recover from mess ups! a log of your last few actions
git reflog
#!/bin/bash
# gitbackup.sh
# Create a shell script and name it whatever you want, like backup.sh
# How to backup/sync all of your dotfiles with Github
# There are many dotfiles in my machine such as .alias, .vimrc, .zshrc, .gitconfig etc...
# Initiate an empty Git repository with $ git init and connect the local repo to newly created repo
with $ git remote add [email protected]:yourusername/yourrepo.git
# check to see is git command line installed in this machine
IS_GIT_AVAILABLE="$(git --version)"
if [[ $IS_GIT_AVAILABLE == *"version"* ]]; then
echo "Git is Available"
else
echo "Git is not installed"
exit 1
fi
########
# make execudable
chmod +x gitbackup.sh.
# Run the script with $
./gitbackup.sh
# this is open the cronjobs table in vim mode use i for insert mode
crontab -e and add your script path and time you want to run the script for example
crontab -e
# this is run the script every minutes
*/10 * * * * cd /Users/macp15/Projects/dotfiles/scripts/gitbackup && ./gitbackup.sh
# display list of cron jobs
crontab -l
########
## Check git status ##
gs="$(git status | grep -i "modified")"
echo "${gs}"
# If there is a new change
if [[ $gs == *"modified"* ]]; then
echo "push"
fi
# The `git show` command may _show_ files from a specific branch or revision
git show origin/gh-pages:index.html
# Bash tip, capturing standard out & error to a variable...
_git_status="$( { git status; } 2>&1 )"
tee "./index.html" <<<"$(git show gh-pages:index.html)"
#==============================##==============================#
# CMD git #
#==============================##==============================#
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command git in a clear format. This allows users to quickly access the needed information for git without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for git are a valuable resource to work efficiently and purposefully.
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
█║▌│║█║▌★ KALI ★ PARROT ★ DEBIAN 🔴 PENTESTING ★ HACKING ★ █║▌│║█║▌
██╗ ██╗ ██████╗ ██████╗ ██╗ ██╗███████╗██████╗
████████╗██╔══██╗██╔═══██╗╚██╗██╔╝██╔════╝██╔══██╗
╚██╔═██╔╝██║ ██║██║ ██║ ╚███╔╝ █████╗ ██║ ██║
████████╗██║ ██║██║ ██║ ██╔██╗ ██╔══╝ ██║ ██║
╚██╔═██╔╝██████╔╝╚██████╔╝██╔╝ ██╗███████╗██████╔╝
╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═════╝
█║▌│║█║▌ WITH COMMANDLINE-KUNGFU POWER █║▌│║█║▌
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
Feedback
Was this page helpful?
Glad to hear it! Please tell us how we can improve.
Sorry to hear that. Please tell us how we can improve.