Skip to content

Instantly share code, notes, and snippets.

@allex
Last active December 14, 2015 03:09
Show Gist options
  • Save allex/5018623 to your computer and use it in GitHub Desktop.
Save allex/5018623 to your computer and use it in GitHub Desktop.

NOTE.md

GistID: 5018623
GistURL: <https://gist.github.com/allex/5018623>
Author: Allex Wang (http://iallex.com)

GIT

  • Edit an incorrect commit message in git

    git commit --amend -m "your new message"

    To amend previous commit make the changes you want and stage those changes, and then use

    git commit --amend

    to amend previous commit, and keep the same log message use

    git commit --amend -C HEAD

    to fix the previous commit by removing it entirely use

    git reset --hard HEAD^

    If you want to edit more than one commit message use

    git rebase -i HEAD~COMMIT_COUNT

    Do not forget to replace COMMIT_COUNT with number of commits that you want to edit. This command launches editor, mark the first commit (the one that you want to change) as "edit" instead of "pick", then save and exit your editor.

    make the change you want to commit then:

    git commit --amend
    git rebase --continue
    
  • See an old version of a file?

    git show REVISION:path/to/file

    For example, to show the 4th last commit of the file src/main.c, use: git show HEAD~4:src/main.c

  • Quickly review the changes made to a file using the diff command:

    git diff

    Then to revert a specific file to that commit use the reset command: git reset You may need to use the --hard option if you have local modifications.

    A good workflow for managaging waypoints is to use tags to cleanly mark points in your timeline. I can't quite understand your last sentence but what you may want is diverge a branch from a previous point in time. To do this, use the handy checkout command:

    git checkout git checkout -b

    You can then rebase that against your mainline when you are ready to merge those changes:

    git checkout git rebase master git checkout master git merge

  • Initialized empty Git repository

    git init --bare bare

  • Git alaiases defines

    alias gitdiff-1="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 2|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git diff" alias gitdiff-2="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 3|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git diff" alias gitdiff-3="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 4|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git diff"

    alias gitlog-1="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 2|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git log --summary" alias gitlog-2="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 3|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git log --summary" alias gitlog-3="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 4|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git log --summary"

  • Show the "current revision" of "HEAD" is simulated by using this:

    git rev-list HEAD | wc -l

    But what if the client tells me that there is a bug in "revision" 1302 ? For this I added the following to the [alias] section of my ~/.gitconfig:

    show-rev-number = !sh -c 'git rev-list --reverse HEAD | nl | awk "{ if(\$1 == "$0") { print \$2 }}"'

  • Git diff -w ignore whitespace only at start & end of lines

    git diff --ignore-space-at-eol

  • ignore whitespace. git diff -w (--ignore-all-space)

  • .gitignore file not ignoring

    http://stackoverflow.com/questions/1139762/gitignore-file-not-ignoring

    Just got the answer from the IRC channel. Running command:

    git rm -r --cached . This removes everything from the index, then just run:

    git add . Commit it:

    git commit -m ".gitignore is now working"

    To untrack a file that has already been added/initialized to your repository, ie stop tracking the file but not delete it from your system use: git rm --cached filename

    Yes - .gitignore system only ignores files not currently under version control from git. I.e. if you've already added a file called test.txt using git-add, then adding test.txt to .gitignore will still cause changes to test.txt to be tracked. You would have to git-rm test.txt first, commit that change. Only then will changes to test.txt be ignored.

    If you are trying to ignore changes to a file that's already tracked in the repository (e.g. a dev.properties file that you would need to change for your local environment but you would never want to check in these changes) than what you want to do is:

    git update-index --assume-unchanged If you wanna start tracking changes again

    git update-index --no-assume-unchanged


    git rm -r --cached . git add . git reset HEAD

    cat $(git rev-parse --show-toplevel)/.gitIgnore | sed "s//$//" | grep -v "^#" | xargs -L 1 -I {} find $(git rev-parse --show-toplevel) -name "{}" | xargs -L 1 git rm -r --cached

  • Force git to overwrite local files on pull

    http://stackoverflow.com/questions/1125968/force-git-to-overwrite-local-files-on-pull

    git fetch --all git reset --hard origin/master git fetch downloads the latest from remote without trying to merge or rebase anything. Then the git reset resets the master branch to what you just fetched.

    Sometimes just clean -f does not help. In case you have untracked DIRECTORIES, -d option also needed:

    git reset --hard HEAD git clean -f -d git pull

  • how to rename a repository on github

    Just use the edit option in github, then go to your local repository and rename the remote. Like this:

    First remove it:

    git remote rm origin then add back the new name

    git remote add origin git@github.com:"yourname"/"projectname".git Now it should be good to go.

    http://stackoverflow.com/questions/4777535/how-do-i-rename-a-github-repository-via-their-api/6603754#6603754

  • git diff between branches

    You can diff them via git with:

    git diff branch:UNREADME master:README You can get a repository artifact to standard output with git show:

    git show branch1:UNREADME

    http://stackoverflow.com/questions/3338126/git-how-to-diff-the-same-file-between-two-different-commits-on-the-same-branch

  • git config --global core.warnambiguousrefs false If you just want to get rid of warning, set core.warnAmbiguousRefs to false:

    git config --global core.warnambiguousrefs false If you want this behavior only for single repository, omit --global flag.

    git log --diff-filter=D --summary

    List all deleted files in git repository and rm it.

    git ls-files --deleted | xargs git rm

  • git submodule

    Git - easy way pull latest of all submodules

    git submodule update --init git submodule foreach git pull git submodule foreach git pull origin master git pull --recurse-submodules git submodule foreach --recursive git submodule update --init

  • git push and pull default destinations

    git push No refs in common and none specified; doing nothing. Perhaps you should specify a branch such as 'master'. fatal: The remote end hung up unexpectedly error: failed to push some refs to 'git@localhost:stivlo-repo'

    git push origin master Counting objects: 3, done. Writing objects: 100% (3/3), 220 bytes, done. Total 3 (delta 0), reused 0 (delta 0) To git@localhost:stivlo-repo

    • [new branch] master -> master

    git pull You asked me to pull without telling me which branch you want to merge with, and 'branch.master.merge' in your configuration file does not tell me, either. Please specify which branch you want to use on the command line and try again (e.g. 'git pull '). See git-pull(1) for details.

    If you often merge with the same branch, you may want to use something like the following in your configuration file:

     [branch "master"]
     remote = <nickname>
     merge = <remote-ref>
    
     [remote "<nickname>"]
     url = <url>
     fetch = <refspec>
    

    See git-config(1) for details.

    $ git branch --set-upstream master origin/master Branch master set up to track remote branch master from origin.

    $ git pull Already up-to-date.

    http://blog.mikepearce.net/2010/05/18/the-difference-between-git-pull-git-fetch-and-git-clone-and-git-rebase/

    git checkout localBranch git pull origin master git branch

    master * localBranch

    The above will merge the remote "master" branch into the local "localBranch".

    Git fetch

    Fetch is similar to pull, except it wonnt do any merging.

    view sourceprint? $&gt; git checkout localBranch $&gt; git fetch origin remoteBranch $> git branch master * localBranch remoteBranch

  • Print the object name of the current commit:

    http://www.kernel.org/pub/software/scm/git/docs/git-rev-parse.html

    $ git rev-parse --verify HEAD $ git log -1 --pretty=format:%h $ git log --pretty="format:%h %s" $ git log --pretty=format:"%h%x09%an%x09%ad%x09%s"

    $ git log --stat # list all commits and commit messages

  • Give git rebase the number of commits back in time. For 10 commit back in history: git rebase -i HEAD~10

    How do I push amended commit to the remote git repo? ! [remote rejected] master -> master (non-fast forward) If you know that you are the only person pushing and you want to push an amended commit or push a commit that winds back the branch, you can 'force' git to update the remote branch by using the -f switch.

    git push -f origin master

    However, if you really, really want to push an amended commit, you can do so like this:

    git push origin +master:master

    The leading + sign will force the push to occur, even if it doesn't result in a "fast-forward" commit. (A fast-forward commit occurs when the changes you are pushing are a direct descendant of the changes already in the public repo.)

  • How can I configure a default remote branch for when I git pull?

    git branch --set-upstream master origin/master

  • Here is the complete solution:

    In your repository, add a file .git/info/attributes which contains: *.py filter=tabspace

    Now run the commands: git config --global filter.tabspace.smudge 'unexpand --tabs=4 --first-only' git config --global filter.tabspace.clean 'expand --tabs=4 --initial'

    You may now check out all the files of your project. You can do that with: git checkout HEAD -- **

SVN

  • get currently dir svn url svn info | egrep '^URL: (.*)' | sed s/URL:\ //

    svn propset svn:ignore cache .

    This will overwrite any current value of svn:ignore. You an edit the value with: svn pe svn:ignore .

  • adds all new files for subversion alias sa="svn status | grep "^?" | sed -e 's/? *//' | sed -e 's/ /\ /g' | xargs svn add"

  • Quick SVN script for automatically adding and deleting files

    http://ceardach.com/comment/213

    svn add svn status .|grep "^?"|awk '{print $2}' svn delete svn status .|grep "^\!"|awk '{print $2}'

    svngrep()
    {
        # Modified from
        # http://ceardach.com/
        if test -z "$2"; then
            svn status | egrep "${1}" | awk '{print $2}'
        else
            svn ${2} `svn status | egrep "${1}" | awk '{print $2}'`
        fi
    }
    

    svn revert --depth=infinity . svn diff -r HEAD|PREV|COMMITTED|{DATE}|NUMBER svn diff -r HEAD:PREV

  • How to list all svn externals recursively You can use the following command to list all the svn externals in a directory structure.

    svn propget svn:externals -R

  • set svn externals. svn propset svn:externals '{NAME} {URL}' {BASE_DIR}

  • sometimes you want to check out only a few directories in source tree,

    rather than check out them individually, you can check out the top directory to be able to commit files in there directory together without having to download too many files from svn server, here is how you can do: check out top directory without content

    svn co --depth empty https://svn.server.com/trunk trunk cd trunk svn update dir1 dir2 dir3

    here we go, you have checked out dir1 dir2 dir3 in trunk

VIM

  • VIM Merge multiple blank lines into one blank line without touching the single blank lines.

    :%s/^\s*$//g :g/^_$\n_^$/d

    :!tail -n -6 % | paste -d '\0' % - | head -n 5

Linux Commonds

  • mount -t iso9660 /home/xxxx.iso /mnt -o loop

  • find & rm mkdir -p foo/bar find foo -name bar -exec rm -rf {} ;

    foo will get deleted as I desired, however this pops out on standard error: find: foo/bar: No such file or directory

    solution: find foo -name bar -maxdepth 1 -exec rm -r {} ;

    find /bla/* -mtime +8 | rm find /bla/* -mtime +8 -print0 | xargs -0 rm

    find . -not -iwholename '.svn' find . ! -regex ".[/].svn[/]?." find . | grep -v '.svn'

    find . -type f -exec wc -l {} ;

    list dir name exclude current dir and dots

    find ls -l | awk ' /^d/ { print $NF } ' -type d -name "*" -print | grep -v '/.'

    export GREP_OPTIONS="--binary-files=without-match --color=auto --devices=skip --exclude-dir=CVS --exclude-dir=.libs --exclude-dir=.deps --exclude-dir=.svn"

    tar -cvf logswitch.tar find *.log* -mtime +5 && find .log -mtime +5 -exec rm {} ; tar -cvvf logswitch.tar find *.log* -mtime $Days --remove-files

  • python -m SimpleHTTPServer

  • Ubuntu reset menu bars. killall gtk-window-decorator gtk-window-decorator --replace

  • restart x-server from the command line? sudo service lightdm restart

    Depending if you use lightdm (ubuntu 11.10 and later), gdm (gnome) or kdm (KDE) you can use one of the following commands:

    sudo restart lightdm
    sudo restart gdm

    or

    sudo restart kdm

  • To replicate your packages selection on another machine (or restore it if re-installing), you can run this: dpkg --get-selections > ~/my-packages

    Then move the file "my-packages" to the other machine, and there run: sudo dpkg --set-selections < my-packages && sudo apt-get dselect-upgrade

    When you run the command above, all packages that were marked as "selected" will be installed in a batch and all packages marked as "deselected" will be removed, if present. This is a very handy feature.

    drm:i915_gem_create_mmap_offset ERROR failed to allocate offset for bo 0

    Unhandled exception: unimplemented function mssign32.dll.PvkGetCryptProv called in 32-bit code (0x7b839ce2).

    "org.ayatana.bamf.view" doesn't exist

  • GPG error: http://ppa.launchpad.net jaunty Release: The following signatures couldn't be verified because #the public key is not available: NO_PUBKEY sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys

  • Mount NTFS winxp d:/ -> (data)

    /dev/sda5 /mnt/data ntfs quiet,defaults,locale=en_US.utf8,umask=022,uid=1000,gid=1000 0 0

  • sum

    sha1sum file md5sum file

    find . -type f -print0 | xargs -0 rename �y/A-Z/a-z/�

  • How do I make find exclude hidden files (.files) find . -type f -not -name ".*"

    grep -v ^# /etc/apt/*.list | sort | uniq -c | sort

  • restart smbd sudo /etc/init.d/smbd restart service smbd restart

  • copy multiple files sudo cp ~/var/log/{dpkg,apt/history}.log ~/apt-logs

  • list kernel files (/etc/grub.d/10_linux) list = for i in /boot/vmlinuz-* /boot/vmlinux-* /vmlinuz-* /vmlinux-* /boot/kernel-*; do echo "$i"; done

  • Loop mv files for i in $(find . -iname "-3.0.0-17-"); do sudo mv $i abc/; done;

    find . -mindepth 1 -maxdepth 1 -type d -printf "%P\n"

    /etc/xdg/autostart/

    stopping zeitgeist logging on ubuntu http://johanharjono.com/archives/836

    zeitgeist-daemon --replace

  • How To Delete And Disable Recent History In Ubuntu [Tip]

    rm ~/.local/share/zeitgeist/activity.sqlite zeitgeist-daemon --replace rm ~/.local/share/recently-used.xbel

  • usermod -a -G vboxusers allex

  • Find and Kill a Process that is Using a Particular Port in Ubuntu

    sudo netstat -lpn | grep :8087

    or

    kill lsof -t -i:4444 kill -9 netstat -lanp --protocol=inet | grep 4444 | awk -F" " '{print $7}' | awk -F"/" '{print $1}' lsof -n | grep TCP | grep LISTEN | grep 8087

  • How to find which service is listening on a given port sudo netstat --tcp --udp --listening --program sudo lsof +M -i4 sudo fuser -v 3143/tcp

    bzcat t.tar.bz2

  • restore defaut gnome-terminal gconftool -t string -s /desktop/gnome/applications/terminal/exec gnome-terminal

  • count file lines find . -name ".c" | wc -l find . -name ".c" | xargs wc -l

    ubuntu-bug $(xprop _NET_WM_PID | awk '{print $NF}')

  • Print access rights in octal format:

    http://www.cyberciti.biz/faq/display-file-or-file-system-status/

    $( stat --format=%a "$line" ) $ stat -c %a /etc/passwd

  • Generate the alphabet from a-z echo $(printf "%c" {a..z}) printf "%c\n" {a..z}

    ssh root:alpine@ipad:22 /etc/hosts

  • These are permissions as listed with the ls command.

    r=read w=write x=executeable s=setuid

    BUILD_HASH=$(date | openssl sha1 | awk -F" " '{print $NF}') $(date | openssl sha1 | grep -oE "[^ ]+$")

    echo -n "foo" | openssl aes-128-cbc -k "key" -base64 -e

    echo 1:2:3:4:5 | rev | cut -d: -f1 | rev 5 echo "1:2:3:4:5" | grep -oE "[^:]+$" 5

    /*jslint debug: true, es5: true, newcap: true, nomen: true, sub: true, browser: true, devel: true, node: true, windows: true, passfail: false */

  • Install Easy Install for Python sudo apt-get install python-setuptools python-dev build-essential

    http://httpd.apache.org/docs/1.3/logs.html http://www.apacheweek.com/features/logfiles

    LogFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i"" combined CustomLog logs/log-full combined

  • list subversion repository's ignore settings svn proplist -v -R [TARGET] svn propedit svn:ignore .

  • Ignore Patterns for Git Users svn propset svn:ignore -F .gitignore . svn update --set-depth infinity

  • git-svn apt-get install git-svn

  • Switch display from laptop to external monitor xrandr --output VGA1 --primary

  • It sounds like you aren't able to resolve domains via DNS. Assuming this is the case, you can likely fix it by adding a dns-nameservers line to /etc/network/interfaces

    auto eth0 iface eth0 inet static address 192.168.2.2 netmask 255.255.255.0 gateway 192.168.2.1 dns-nameservers 192.168.2.1 and then running

    resolvconf -u as root to update /etc/resolv.conf.

  • Change timeout delay for Sudo command password in Ubuntu

    sudo visudo

    find the line says: Defaults env_reset

    change it into Defaults env_reset , timestamp_timeout=x

    here change “x” to the minutes you want the terminal remember. Note:You can set “x” to -1,so that the terminal will remember sudo password until you log-out or close this terminal window.To force terminal ask password again when running sudo command,use:

    ERROR: Could not apply the stored configuration for monitors

  • Ubuntu 12.04 detect my screen resolution?

    xrandr --newmode $(cvt 1920 1080 60 | grep Mode | sed -e 's/.*"/1920x1080/') xrandr --addmode VGA1 1920x1080

    sudo apt-get remove indicator-power

  • get ubuntu releaase name

    echo $(lsb_release -sc)
    >> quantal
    
  • How to : Remove the Guest Session from the Logon screen in Ubuntu 11.10

    Step 1: sudo vi /etc/lightdm/lightdm.conf

    Step 2: Add the following line at the bottom. allow-guest=false

    Step 3: Reboot

  • Remove Old Kernels in Ubuntu

    uname -r
    dpkg --list | grep linux-image
    
  • kill the process running on specific port in linux

    lsof -w -n -i tcp:8080
    kill -9 `lsof -t -i:8087`
    kill -9 $(lsof -w -n -i tcp:8087 | grep "python" | awk -F" " '{print $2}')
    

    http://superuser.com/questions/322363/how-do-i-find-and-kill-process-running-on-a-certain-port

  • resolve apt-get BADSIG GPG errors?

    sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 54422A4B98AB5139
    

    links

    for f in $(ls); do ln -s $(readlink -f $f) ~/.icons/Custom-Icons/status/24/$f; done
    
  • Remove the Guest Session from Ubuntu

    sudo vi /etc/lightdm/lightdm.conf allow-guest=false

    http://www.liberiangeek.net/2012/03/remove-the-guest-session-from-ubuntu-12-04-precise-pangolin/

  • poweroff VM

    VBoxManage controlvm winxp poweroff

  • How to Change the Default Text Editor on Ubuntu

    vi ~/.local/share/applications/defaults.list

    [Default Applications]
    text/plain=gvim.desktop
    

    That is, if you plan on using gvim, of course. Replace gvim with the appropriate filename otherwise (e.g., scite.desktop).

    Another option That's works, but you can also try:

    sudo update-alternatives --config editor sudo update-alternatives --config gnome-text-editor

    The default handler for text/* (plain, html, xhtml, xml, etc) is /usr/bin/editor for console applications and /usr/bin/gnome-text-editor for the gnome desktop. To change it you should run one (or both) of the above commands. update-alternatives(8) [man 8 update-alternatives] has a deep explanation of how this works.

  • Folder Renaming After Tar Extraction Manually create folder, and strip components from tarball:

    archive=my.tar.gz
    mkdir ${archive%.tar*} 
    tar --extract --file=${archive} --strip-components=1 --directory=${archive%.tar*}
    
  • SSH sudo commond ERROR: sudo: sorry, you must have a tty to run sudo

    vi /etc/sudoers comment out: #Default requiretty

  • Uninstalling Canonical Landscape On Ubuntu

    To remove the text that says: “Graph this data and manage this system at https://landscape.canonical.com/” while keeping the useful system information, edit (or add) the configuration file that controls the Landscape client:

    sudoedit /etc/landscape/client.conf

    Edit this file to include the section: [sysinfo] exclude_sysinfo_plugins=LandscapeLink

    This is a better solution than editing the Message of the Day script (/etc/update-motd.d/50-landscape-sysinfo) because it survives updates to the Landscape and update-motd packages.

    Test this change by running: /etc/update-motd.d/50-landscape-sysinfo

    It should look like:

    System information as of Mon Mar 19 06:46:31 GMT 2012
    
    System load:  0.0               Temperature:         59 C
    Usage of /:   8.1% of 39.85GB   Processes:           92
    Memory usage: 20%               Users logged in:     1
    Swap usage:   0%                IP address for eth0: 192.168.0.1
    

    This article was updated with j's suggestion from the comments. Many thanks to j for making it even simpler!

    sudo perl -pi -e 's/landscape-sysinfo/landscape-sysinfo --exclude-sysinfo-plugins=LandscapeLink/g' /etc/update-motd.d/50-landscape-sysinfo

    sudo aptitude remove landscape-client landscape-common

  • SSH login welcome message

    /etc/update-motd.d

    software-properties

  • Disable (or remove) the Shopping Lens

    sudo apt-get remove unity-lens-shopping

  • install easy_install

    sudo apt-get install python-setuptools

  • cygwin share clipboard

    http://vim.wikia.com/wiki/Using_the_Windows_clipboard_in_Cygwin_Vim

    !cat /dev/clipboard

  • How to fix missing GPG keys?

    apt-get update 2> /tmp/keymissing; for key in $(grep "NO_PUBKEY" /tmp/keymissing |sed "s/.*NO_PUBKEY //"); do echo -e "\nProcessing key: $key"; gpg --keyserver subkeys.pgp.net --recv $key && sudo gpg --export --armor $key | apt-key add -; done

    1.6.11-11.el5_9

  • report file system disk space usage

    df -BG

  • ssh -d forward for socket5 proxy

    ssh -p 8022 -N -D 0.0.0.0:7070 root@localhost

  • Repairing apt-get database

    sudo dpkg --configure -a
    sudo apt-get -f install
    sudo apt-get install debconf --reinstall
    
  • partion size, foleder useage

    df -h
    du -h
    du | sort -k 1 -g ( -g, --general-numeric-sort )
    du --max-depth=1 -h -a
    
  • list files size greater than 100k

    du --max-depth=1 -a | awk '$1 > 100'

  • list files greater than 100, and just print file path.

    du --max-depth=1 -a | awk '$1 > 100{print $2}'

  • base64 encode/decode

    http://stackoverflow.com/questions/8110294/nodejs-base64-image-encoding-decoding-not-quite-working

    echo QWxhZGRpbjpvcGVuIHNlc2FtZQ== | base64 --decode openssl enc -base64 -d <<< SGVsbG8sIFdvcmxkIQo=

    decode () { echo "$1" | base64 -d ; echo }

Linux Notes

Misc Logs

  • (google) GAE

    Application-specific passwords upexmrogoshpfxby No need to memorize this password. You should need to enter it only once. Spaces don't matter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment