Ask HN: Share your favourite bash/zsh aliases

38 points by yanis_t ↗ HN
I'll start by adding the most essential.

alias o="open"

alias x="exit"

alias g="git"

alias gs='git status'

alias gd='git diff'

alias g-='git checkout -'

alias serve='python -m SimpleHTTPServer 8000'

alias mem='top -l1 | grep PhysMem'

74 comments

[ 35.2 ms ] story [ 325 ms ] thread

  alias l='ls -1F'

    # eXpand anything
    alias xx="atool -x"   
( http://www.nongnu.org/atool/ )

The incredible amount of time this has saved over the years is great, but the real benefit never having remember either inspect archive files for the initial directory or remember to do this dance:

    % mkdir foo
    % cd foo
    % tar zxvf /path/to/bar.tar.gz  # or "unzip foo.zip" or "7x x foo.7z" etc
    % mv bar-1.2.3 ..
    % cd ..
    % rmdir foo
I have found this bash function a while ago. It doesn't save all the steps, but it shouldn't be too difficult to add them, too.

https://gist.github.com/Fannon/41b0a6104435943cd826

I used to use something similar, but atool is far superior. It handles quite a few situations, but the most important is that it will decompress into the current directory (as a normal "tar zxvf foo.tar.gz" or "unzip foo.zip") if-and-only-if there was exactly one file or directory at the top level of the in the archive. If the archive was packaged badly, it will leave the resulting files in the temporary directory it creates. Also, atool leave the file(s) in the temporary directory in the event of a name collision, so you protected from the risk of clobbering existing files.

Without atool you have to either 1) create a temporary dir youself and do the dance I showed above, or 2) always inspect every archive before you decompress it to see if it has multiple top-level files, or 3) accept that typing "tar xvf" or similar will sometimes spam your current directory (often $HOME) with thousands of files.

Similar to how git tends to remove mental blocks around branching (you not longer have ot worry about the cost of making an arbitrary change), atool frees you from having to worry about how an archive was created. This has, in practice, saved huge amount of time and mental effort.

(comment deleted)
The essential and usual one handed listing aliases:

  alias l='ls -laFT'
  alias ll='ls -1aF'
  alias k='ls -laFTrt'
  alias kk='ls -1aFrt'
Some X + tee magic for logging.

  alias xlog='mv .xlog.txt .xlog.txt.old && startx -- -nolisten tcp 2>&1 | tee . xlog.txt > /dev/console'

  alias xdbg='mv .xdbg.txt .xdbg.txt.old && startx -- /usr/X11R6/bin/X -keepPriv 2>&1 | tee .xdbg.txt > /dev/console'
And in ~/.xinitrc run an oddly colored xterm with /dev/console output:

  xterm -C -fg '#b00020' -geometry 80x38+0+0 &
Most folks don't start X manually but when working on X itself, extra logging can often help.
I use oh-my-zsh aliases

    ...=../..
	....=../../..
	.....=../../../..
	......=../../../../..
	1='cd -'
	2='cd -2'
	3='cd -3'
	4='cd -4'
	5='cd -5'
	6='cd -6'
	7='cd -7'
	8='cd -8'
	9='cd -9'
	_=sudo
	afind='ack-grep -il'
	d='dirs -v | head -10'
	g=git
	ga='git add'
	gaa='git add --all'
	gap='git add --patch'
	gb='git branch'
	gba='git branch -a'
	gbr='git branch --remote'
	gc='git commit -v'
	'gc!'='git commit -v --amend'
	gca='git commit -v -a'
	'gca!'='git commit -v -a --amend'
	gcl='git config --list'
	gclean='git reset --hard && git clean -dfx'
	gcm='git checkout master'
	gcmsg='git commit -m'
	gco='git checkout'
	gcount='git shortlog -sn'
	gcp='git cherry-pick'
	gcs='git commit -S'
	gd='git diff'
	gdc='git diff --cached'
	gdt='git difftool'
	gg='git gui citool'
	gga='git gui citool --amend'
	ggpnp='git pull origin $(current_branch) && git push origin $(current_branch)'
	ggpull='git pull origin $(current_branch)'
	ggpur='git pull --rebase origin $(current_branch)'
	ggpush='git push origin $(current_branch)'
	gignore='git update-index --assume-unchanged'
	gignored='git ls-files -v | grep "^[[:lower:]]"'
	git-svn-dcommit-push='git svn dcommit && git push github master:svntrunk'
	gk='gitk --all --branches'
	gl='git pull'
	glg='git log --stat --max-count=10'
	glgg='git log --graph --max-count=10'
	glgga='git log --graph --decorate --all'
	glo='git log --oneline --decorate --color'
	globurl='noglob urlglobber '
	glog='git log --oneline --decorate --color --graph'
	glp=_git_log_prettily
	gm='git merge'
	gmt='git mergetool --no-prompt'
	gp='git push'
	gpoat='git push origin --all && git push origin --tags'
	gr='git remote'
	grba='git rebase --abort'
	grbc='git rebase --continue'
	grbi='git rebase -i'
	grep='grep  --color=auto --exclude-dir={.bzr,.cvs,.git,.hg,.svn}'
	grh='git reset HEAD'
	grhh='git reset HEAD --hard'
	grmv='git remote rename'
	grrm='git remote remove'
	grset='git remote set-url'
	grt='cd $(git rev-parse --show-toplevel || echo ".")'
	grup='git remote update'
	grv='git remote -v'
	gsd='git svn dcommit'
	gsps='git show --pretty=short --show-signature'
	gsr='git svn rebase'
	gss='git status -s'
	gst='git status'
	gsta='git stash'
	gstd='git stash drop'
	gstp='git stash pop'
	gsts='git stash show --text'
	gts='git tag -s'
	gunignore='git update-index --no-assume-unchanged'
	gunwip='git log -n 1 | grep -q -c "\-\-wip\-\-" && git reset HEAD~1'
	gup='git pull --rebase'
	gvt='git verify-tag'
	gwc='git whatchanged -p --abbrev-commit --pretty=medium'
	gwip='git add -A; git ls-files --deleted -z | xargs -r0 git rm; git commit -m "--wip--"'
	history='fc -l 1'
	l='ls -lah'
	la='ls -lAh'
	ll='ls -lh'
	ls='ls -G'
	lsa='ls -lah'
	md='mkdir -p'
	please=sudo
	po=popd
	pu=pushd
	rd=rmdir
	run-help=man
	which-command=whence
Do these really save that much time?

I stopped using oh-my-zsh because of these. There is a popular program called 'gap' which got over-written by one of these aliases.

I am hooked on most of them at this point, but I can see that being very annoying.
yes they do. I also learnt a bit about git from them glg and git whatchanged ale quite useful.

One problem I had with gulp. I had dir name gulp and zsh got confused weather to go to the dir or execute the cmd.

I laughed at "please=sudo". Never knew about that one.
alias ip="curl icanhazip.com" # Your public IP address

alias diskspace="du -S | sort -n -r |less"

alias pyserver='python -m SimpleHTTPServer'

alias phpserver='php -S localhost:8000'

alias phplog='tail -f /var/log/apache2/error.log'

  alias ..='cd ..'
  alias ...='cd ../..'
  alias ....='cd ../../..'
  alias .....='cd ../../../..'
  alias ......='cd ../../../../..'
   
  # search history (??) and processes (???)
  alias '?=fc -li 1'
  alias '??=fc -li 1 | grep '
  alias '???=ps-grep'
   
  alias m='less'
   
  alias su='sudo -H -s'
   
  # move to trash rather than deleting
  rm='trash-put -v'
   
  # simplify hard to remember command names
  alias pk-show='apt-cache show'
  alias pk-install='sudo apt-get install'
  alias pk-update='sudo apt-get update'
  alias pk-update-upgrade='sudo apt-get update && sudo apt-get upgrade'
  alias pk-uu=pk-update-upgrade
  alias pk-remove='sudo apt-get remove'
  alias pk-debinst='sudo dpkg -i'
  pk-search () {
    apt-cache search $1 | sort | egrep "${1}|$"
  }
alias cp='cp -i'

prompts when you overwrite something using cp ("oops, wrong folder")

alias rm='rm -I'

prompts when you delete more than three files ("oops, a space too much in rm ./ *")

  alias sucs='sort | uniq -c | sort -n’ # Makes a histogram of line-based input
  
  # Example
  $ echo c c c c b c b a a a | xargs -n1 | sucs
   2 b
   3 a
   5 c
alias scp='rsync --archive --compress-level=3 --copy-links --partial --inplace --progress --rsh=ssh -r'
But now you can't use scp, right? Or did you alias that too?
Just prepend the command with `\`, that disables aliases.
Well in zsh running =scp would run /usr/bin/scp not the alias.
Here are a few I haven't seen in a lot of places but come in really handy.

First, alias this on Linux to get the 'open' command to work like OSX (e.g. 'open file.pdf'). It shadows a real 'open' command, but I have never used it, so no big loss :

  alias open='xdg-open'
The second one I use all the time. A process that is stuck on I/O (or other uninterruptible syscalls), or even a Python interpreter stuck in a C extension, won't always respond well to Ctrl-C. However, Ctrl-Z (suspend) and this alias (kills the last suspended process group) do work relatively well :

  alias killit='kill -9 %%'
This one I use a lot for copying the output of a command to the clipboard. Just run 'command | pbcopy' and then Ctrl-V elsewhere. pbcopy is actually an OSX command, I aliased it on Linux for ease of use :

  alias pbcopy='xclip -selection clipboard'
  alias pbpaste='xclip -selection clipboard -o'
This one runs a program under GDB. You can run e.g. 'gdbrun =python test.py' and debug C extensions more easily:

  alias gdbrun='gdb -ex=r --args'
If you're a virtualenv user, I use this one-liner to start load a virtualenv named after the current directory:

    alias v='workon "${PWD##*/}"'
Also, I really like the -p flag of mkdir (creating child directories as needed, without failing if one doesn't exist)

    alias mkdir='mkdir -p'
    # i.e. mkdir ./a/b/c/
I use most of the oh-my-zsh builtins. The git ones save a ton of time and G='|grep' is brilliant.

    alias GD='git diff HEAD~1 HEAD'
    alias grv='git review'
    alias gunmod='git status | grep "modified" | awk "{print \$2}" | xargs -I{} git checkout -- {}'
    alias gv='gvim --remote-silent'
    alias json='| python -m json.tool'
    alias vg='vagrant'
    alias ans='ansible '
    alias ansp='ansible-playbook '
    alias vv='virtualenv venv'
    alias vvp='venv/bin/python'
    alias vvpi='venv/bin/python setup.py develop'
    alias yt='cd $HOME/downloads; youtube-dl --verbose'
    alias yt3='cd $HOME/downloads; youtube-dl --verbose --extract-audio --audio-format mp3 '
I keep all of my shell history, right now it think it goes back ~3 years, so every now and then I filter it by frequency and check if I am using a command often enough to justify an alias. Works quite well

  > alias json='| python -m json.tool'
Is the beginning pipe intended? If I just run 'python -m json.tool' then it starts reading from stdin by itself (and works as intended). And with the pipe, I can’t seem to make the alias work.

  $ echo  '{ "foo": 1234}' | json
  -bash: syntax error near unexpected token `|'

  $ json
  -bash: syntax error near unexpected token `|'
yeah, thats my bad, A recent addition and I must have copied too much of the command line when adding it.
Have you taken a look at the top dotfiles on Github ( https://dotfiles.github.io/ )? They have a pretty good set of aliases, especially the basics and many for git.

For example, YADR is pretty good ( https://github.com/skwp/dotfiles ).

Of the ones not listed already in this thread, a few standards that are great to have:

L - less

H - | head

T - | tail

G - | grep

C - | wc -l

N - /dev/null

S - | sort

_ - sudo

the dotfiles site seems a good idea but for some reason I'm basically unable to read the text. Even highlighting some with the mouse doesn't help.
Assuming functions count:

    # git branch ahead/behind another
    function gahead() {
      # use first argument or master
      original=${1-master}

      # use the second argument or current branch if not given
      current=`git branch | grep \* | sed s/\*\ //`
      compare=${2-$current}

      # run git rev-list and capture numbers returned
      result=`git rev-list --left-right --count $original...$compare`

      # print numbers in a pretty message
      numbers=($result);
      echo -e "$Red-$Color_Off $compare is currently $IRed${numbers[0]}$Color_Off commits behind $original";
      echo -e "$Green+$Color_Off $compare is currently $IGreen${numbers[1]}$Color_Off commits ahead of $original";
    }
Edit: if it's not clear you would use this like:

    $ gahead #checks current branch against master
    $ gahead development #checks current branch against development
    $ gahead development foo #checks foo branch against development
NB: this is checking local branches, not remote branches.
On Mac OS, copy the CWD to the clipboard:

alias cpcd="echo -ne \$(pwd) | pbcopy"

Useful when you have a file picker in front of you, but you know you have a terminal already in the directory you want. Switch to the term, cpcd, switch to the file picker, Go to folder (⌘-Shift-G), Paste (⌘-V).

when you have a terminal open in a directory, but another app has a file picker box.

Why not just do 'open .' in Terminal/iTerm 2?

    alias lc="ls -C | less"

    alias ll="ls -lh"

    function mkd() {
        if [[ $#  == 0 ]] ; then
            return
        fi

        mkdir "$1"
        cd "$1"
    }
I don't have many. Tab completion on linux is usually enough.

    alias i='i3-msg -q exec --'
    alias jql='jq . -C | less -R'
Also bindings:

    bind -m vi-command -x '"\C-n": new-term-here'
    bind -m vi-insert  -x '"\C-n": new-term-here'

    #which is `i gnome-terminal --working-directory="$PWD"`
My most used aliases would probably have to be for the git commands. Each git command, I have aliased to the name of the command, preceded with the letter 'g'. So:

  alias gadd='git add'
and so on.

I find the oh-my-zsh git plugin's default aliases to be unintuitive and hard to remember. Simply not having to type 'git ' before everything is good enough for me.

has always served me well - `alias yolo='git rm -f * && git commit -am "yolo" && git push -f origin master'`

  # Fast shortcuts
  alias c='clear'
  alias r='reset'
  alias q='exit'

  alias cd..="cd .." # I often make this mistake

  # Because sometimes you don't have the time to put this two letters
  alias ..='cd ..'
  alias ...='cd ../..'
  alias -- -="cd -"

  # Doing a fast proxy, good for watching netflix and youtube without restrictions
  alias proxy='ssh -C2qTnN -D 8080'

  # To search process with more details
  alias pp="ps axuf | pager"

  # Because I forget the name :(
  alias explore="ranger"

  # Because NeoVim is awesome :)
  alias vim=nvim

  # Do something and receive a desktop alert when it completes `sudo apt-get install something | alert`
  alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'

  # Search process by name and highlight !
  function psgrep() { ps axuf | grep -v grep | grep "$@" -i --color=auto; }

  # Search for files and page it
  function search() { find . -iname "*$@*" | less; }
You can enable AUTOCD and never have to type CD again. :)

shopt -s autocd

what would a OSX version of alert look like?