User:Gwern/.bashrc


 * 1) !/bin/bash
 * 2) .bashrc


 * 1) Copyright (C) 2006 by gwern
 * 2) Author: Gwern Branwen
 * 3) License: Public domain
 * 4) Where:
 * 5) When: Time-stamp: "2007-06-12 21:30:11 gwern"
 * 6) Keywords: local,customization,shell,bash


 * 1) Commentary
 * 2) There are a number of useful things here. Applications are often protected against
 * 3) system crashes by utility functions A number of utilities automate some things -
 * 4) 'pg' is polymorphic on what it is accessing, 'typo' aids in the quick recording of
 * 5) aliases to permanently fix typos, there is integration into darcs, GHC, screen, Tor etc.

declare -x USER="gwern"
 * 1) ##### GENERAL ##### #
 * 2) umask 0700 #keep private things private
 * 1) umask 0700 #keep private things private
 * 1) umask 0700 #keep private things private

ulimit -c 0 -e 0 -t 10000 -d 536870912 -m 5368709120 -v 536870912 -x 10000
 * 1) Let's not have absurdly generous resource permissions.
 * 2) ulimit -c 0 -e 0 -t 10000 -d 536870912 -i 10000 -m 5368709120 -q 536870912 -v 536870912 -x 10000 #Bastille handles some options

. /etc/bash_completion
 * 1) Let's have neat fancy completions!

declare -x http_proxy="http://127.0.0.1:8118/" declare -x HTTP_PROXY="${http_proxy}"
 * 1) ##### ENVIRONMENT VARIABLES ##### #
 * 2) Yay for anonymous browsing through Tor!
 * 1) Yay for anonymous browsing through Tor!
 * 1) Yay for anonymous browsing through Tor!

declare -x SCREENP=True #default if | $TERM = "screen" ; then declare -x SCREENP=False fi
 * 1) Test once and only once for the presence of screen and a terminal which can use it.
 * 2) Check for 'linux' because Screen/Linux console is set to claim to be 'linux'
 * 3) We set the default to off, just to be safe.
 * 4) This variable will be used later.

declare -x TMOUT=9000
 * 1) if a shell is open a ridiculously long time, close it. Given in seconds.

set -o allexport
 * 1) Give subshells all variables

declare -x LS_COLORS='no=00:fi=00:di=01;34:ln=01;36:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:su=37;41:sg=30;43:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.zip=01;32:*.rar=01;31:*.z=01;31:*.Z=01;31:*.gz=01;31:*.bz2=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.avi=01;35:*.mp4=01;35:*.fli=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.flac=01;35:*.mp3=01;35:*.mpc=01;35:*.ogg=01;35:*.wav=01;35:*.el=01;32:*.txt=03;32:*.xml=03;6:*.pdf=02;36:*.ps=02;36:*.wiki=02;36:*.xhtml=02;36:*.html=02;36:*.torrent=01;37:*.exe=01;32:*.lisp=01;32:*.dat=01;35:*.py=01;32:*.pyo=02;32:*.pyc=02;32:*.log=02;36:*.data=02;36:*.mkv=01;35:*.ogm=01;35:*.hs=01;32';
 * 1) generated by dircolors

declare -x EDITOR="emacs -nw" declare -x CVSEDITOR=$EDITOR
 * 1) Default editor- I am an emacs man

declare -x FCEDIT="emacsclient"
 * 1) Tweaking the fc command via the FCEDIT variable; before it started up
 * 2) the full-blown Emacs - this version starts up a really fast Emacs minus
 * 3) a bunch of functionality.

declare -x ALTERNATE_EDITOR="${FCEDIT}" declare -x VISUAL="${EDITOR}"
 * 1) Following variable is used by emacsclient, so if no emacs is running,
 * 2) emacsclient will make one!

declare -x PAGER='less' declare -x LESS="~eimwC"

declare -x PATH='/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/games:/usr/games/bin:/usr/sbin:/sbin:/usr/share/surfraw:/home/$USER/bin:/opt/ghc/bin'

export CVS_RSH=ssh

export MAILCHECK=0

declare -x MANDWIDTH=80
 * 1) This forces man pages to be served at a terminal width of 80; the reason is
 * 2) because this way the catman and mandb commands will reveal their benefits.

declare -x HISTFILE=~/.history declare -x HISTCONTROL=ignoreboth declare -x HISTFILESIZE=1000 declare -x HISTSIZE=1000 declare -x HISTCONTROL=ignoredups declare -x HISTIGNORE="top:cd /home/*:emacs:sync:update:ls:ll:la:l:pwd:exit:mc:su:df:clear:fg:bg:&:exit:df:cd:h:la:au:ad:mounthd:htop:screen:mc" shopt -s histappend #makes bash append to history rather than overwrite PROMPT_COMMAND='history -a' #write to history whenever"
 * 1) History configuration
 * 1) Thanks to

declare -x FIGNORE=CVS:RCS:_darcs
 * 1) Prevent certain directory names from showing up in completion

declare -x LC_ALL="en_US.utf8"

set -o hashall #Make sure the hash table gets used. set -o noclobber set -o physical
 * 1) ##### SHELL VARIABLES ##### #
 * 1) ##### SHELL VARIABLES ##### #

shopt -s cdable_vars shopt -s cdspell shopt -s checkhash shopt -s checkwinsize shopt -s cmdhist shopt -s dotglob shopt -s expand_aliases shopt -s extglob shopt -s histreedit shopt -s histverify shopt -s hostcomplete shopt -s interactive_comments shopt -s lithist shopt -s no_empty_cmd_completion shopt -s progcomp shopt -s promptvars

stty -ixon
 * 1) disable XON/XOFF flow control (^s/^q)

complete -A setopt set complete -A user groups id complete -A binding bind complete -A helptopic help complete -A alias alias unalias complete -A signal -P '-' kill complete -A stopped -P '%' fg bg complete -A job -P '%' jobs disown complete -A variable readonly unset complete -A file -A directory ln chmod complete -A user -A hostname finger pinky complete -A directory find cd c pushd "`pwd`" mkdir rmdir mkd mkdirs rmd mvd complete -A file -A directory -A user chown complete -A file -A directory -A group chgrp complete -o default -W 'Makefile' -P '-o ' qmake complete -A command man which whatis whereis info apropos complete -A file cat zcat pico nano vi vim view gvim gview rgvim rgview evim eview rvim rview vimdiff elvis emacs edit emacsclient sudoedit red e ex joe jstar jmacs rjoe jpico less zless more zmore p pg zip unzip rar unrar mplayer mp m
 * 1) ##### COMPLETIONS ##### #
 * 1) ##### COMPLETIONS ##### #

rgb_restore='\[\033[00m\]' rgb_red='\[\033[01;31m\]' rgb_green='\[\033[01;32m\]' rgb_white='\[\033[01;37m\]' rgb_std="${rgb_white}"
 * 1) ##### PROMPT SECTION ##### #
 * 2) Commented out because not needed, but retained in case I ever want them.
 * 1) Commented out because not needed, but retained in case I ever want them.
 * 1) Commented out because not needed, but retained in case I ever want them.
 * 1) rgb_black='\[\033[00;30m\]'
 * 2) rgb_firebrick='\[\033[00;31m\]'
 * 1) rgb_forest='\[\033[00;32m\]'
 * 1) rgb_brown='\[\033[00;33m\]'
 * 2) gb_yellow='\[\033[01;33m\]'
 * 3) rgb_navy='\[\033[00;34m\]'
 * 4) rgb_blue='\[\033[01;34m\]'
 * 5) rgb_purple='\[\033[00;35m\]'
 * 6) rgb_magenta='\[\033[01;35m\]'
 * 7) rgb_cadet='\[\033[00;36m\]'
 * 8) rgb_cyan='\[\033[01;36m\]'
 * 9) rgb_gray='\[\033[00;37m\]'

if [ `id -u` -eq 0 ] then rgb_usr="${rgb_red}" else rgb_usr="${rgb_green}" fi

[ -z "$PS1" ] && return
 * 1) If not running interactively, don't do anything

[ -n "$PS1" ] && PS1="${rgb_usr}`whoami`${rgb_std} \W \!${rgb_usr}\\\$${rgb_restore}"

unset rgb_restore  \ rgb_black  \ rgb_firebrick \ rgb_red   \ rgb_forest \ rgb_green  \ rgb_brown  \ rgb_yellow \ rgb_navy  \ rgb_blue  \ rgb_purple \ rgb_magenta \ rgb_cadet  \ rgb_cyan  \ rgb_gray  \ rgb_white  \ rgb_std   \ rgb_usr


 * 1) Aliases & Functions
 * 1) Aliases & Functions

alias +="pushd ." alias _="popd"

alias a="amarok &"

alias apt-get="sudo apt-get" if $SCREENP = True ; then alias aptitude="sudo screen -S "aptitude" aptitude" alias apt="sudo screen -S "aptitude" aptitude" fi

function gentoo_update { (sudo sh -c 'emerge --sync && layman -S; emerge -f --newuse --update world && ntpd -q && emerge --newuse --update world && revdep-rebuild -v -X -i'; update_kernel_nonsafe); } function pywikipedia_update { cd ~/bin/pywikipedia && cvs update & } function roguestar_update { cd ~/bin/roguestar && make update && make && sudo make install; } function system_update { gentoo_update && sudo updatedb; prelink; firefox-prelink; mandb; dload; fc-cache -fsv; } function system_information { environment_validate; findsuid & ii; } function update_kernel_unsafe { sudo sh -c 'cd /usr/src/linux && mount /dev/hda1 /boot; make oldconfig && make & make modules; make install & make modules_install'; } function time_update { sudo ntpd -q; } #sudo ntpdate north-america.pool.ntp.org

alias update_kernel="(update_kernel_unsafe)"

declare -x pm="sudo nice emerge" #default to Gentoo or Debian
 * 1) package management stuff
 * 1) declare -x pm="sudo nice apt-get"

if $SCREENP = True ; then #alias check="sudo screen -S "check" $pm check" alias autoclean="$pm autoclean" alias clean="sudo screen -S "clean" $pm --clean" alias update="sudo screen -S "update" $pm --sync && sudo layman --sync ALL; sudo emerge --update world" alias upgrade="system_information; (pywikipedia_update); (roguestar_update); (gentoo_update); (system_update); logout; exit" alias install="sudo screen -S "install" $pm" alias remove="sudo screen -S "remove" $pm -C" fi

alias search="emerge --search --"
 * 1) alias show="apt-cache show"
 * 2) alias search="apt-cache search"

function bandwidth { usage=`grep eth0 /proc/net/dev | cut -d ':' -f 2 | cut -d " " -f 2`; echo $(( usage / 1000000000 )) gigabytes used. }
 * 1) a replacement for sudo ifconfig eth0

alias band="bandwidth"

alias bzip="bzip2" alias bzip2="nice bzip2 -v -v" alias bunzip2="nice bunzip2 -v"

alias ..="c ../" alias ...="c ../ && c ../" alias ....="c ../ && c ../ && c ../"
 * 1) alias cd="c"

function c        { cd -- "$@"; ls -q --color=auto; }
 * 1) This provides a function which will list contents
 * 2) of a directory upon cd'ing into it. Also, cd will be aliased to this,
 * 3) so it always works, but it will be aliased later in the file, so we
 * 4) don't get a endless naming loop.

alias cdrom="mcdrom" alias mcdrom="mount -t iso9660 -o ro /dev/hdc /mnt/cdrom; mount -t iso9660 -o ro /dev/hdc /mnt/cdrom; pushd .; cd /mnt/cdrom && ls -al" alias umcdrom="popd; umount /mnt/cdrom; eject"

alias cliv="clive -y -q -N -m -L --"

alias clr="clear"

function compress { Z="zip" gz="gzip" bz="bzip2" Zout="/tmp/bestcompress.$$.zip" gzout="/tmp/bestcompress.$$.gz" bzout="/tmp/bestcompress.$$.bz" skipcompressed=1 if [ "$1" = "-a" ] then skipcompressed=0 ; shift fi if [ $# -eq 0 ] then echo "Usage: $0 [-a] file or files to optimally compress" >&2; fi trap "/bin/rm -f -- $Zout $gzout $bzout" EXIT for name do if [ ! -f "$name" ] ; then echo "$0: file $name not found. Skipped." >&2			continue fi if [ "$(echo $name | egrep '(\.zip$|\.gz$|\.bz2$)')" != "" ] ; then if [ $skipcompressed -eq 1 ] ; then echo "Skipped file ${name}: it's already compressed." continue else echo "Warning: Trying to double-compress $name" fi fi $Z < "$name" > $Zout & $gz < "$name" > $gzout & $bz < "$name" > $bzout & wait	# run compressions in parallel for speed. Wait until all are done smallest="$(ls -l "$name" $Zout $gzout $bzout | \  awk '{print $5"="NR}' | sort -n | cut -d= -f2 | head -1)" case "$smallest" in 1 ) echo "No space savings by compressing $name. Left as-is."				;;			2 ) echo Best compression is with compress. File renamed ${name}.zip mv $Zout "${name}.zip" ; rm -f -- "$name" ;;			3 ) echo Best compression is with gzip. File renamed ${name}.gz				mv $gzout "${name}.gz" ; rm -f -- "$name"				;;			4 ) echo Best compression is with bzip2. File renamed ${name}.bz2 mv $bzout "${name}.bz2" ; rm -f -- "$name" esac done }
 * 1) !/bin/sh
 * 2) Thanks to "Wicked Cool Shell Scripts: 101 Scripts for Linux, Mac OS X, and Unix Systems"
 * 3) bestcompress - given a file, try compressing it with all the available
 * 4)  compression tools and keep the compressed file that's smallest, reporting
 * 5)  the result to the user. If '-a' isn't specified, it skips compressed
 * 6)  files in the input stream.

alias cp="cp -v" alias copy="cp --"

alias cruft="sudo cruft && sudo cruft -k"

function changes { if -n `which darcs`  #this is pointless if Darcs isn't even installed then if `darcs whatsnew` != 'No changes!' then echo "There are unrecorded changes."; fi fi }
 * 1) Ask darcs whether there have been any unrecorded edits to important revision controlled stuff.
 * 2) If there have been, then record that fact in a text file. The text file will be stored, and updated by
 * 3) .bash_logout

function defrag { abort {		echo -e "\nAborting" rm -f -- tmpfile dirlist exit 1 }	fail {		echo -e "\nFailed" abort }	declare -i filesize=0 declare -i numfiles=0 declare -i maxsize=`awk '/MemTotal/ {print $2}' /proc/meminfo` (( maxsize-= `awk '/Mapped/ {print $2}' /proc/meminfo` )) (( maxsize/= 2)) if | -a dirlist ; then echo dirlist or tmpfile exists exit 1 fi echo "Creating list of files..." find -xdev -type d -printf "%d\n" | sort -n | uniq > dirlist cat dirlist | while read d;	do find -maxdepth $d -xdev -type d -mindepth $d -printf "\"%p\"\n" | \ xargs --max-procs=0 du -bS --max-depth=0 | \ sort -k 1,1nr -k 2 |\ cut -f2 >> tmpfile if (( $? )) ; then fail fi done rm -f -- dirlist cat tmpfile | while read d;	do find "$d" -maxdepth 1 -xdev -type f -printf "%s\t%p\n" | \ sort -k 1,1nr | \ cut -f2 >> dirlist if (( $? )) ; then fail fi done rm -f -- tmpfile numfiles=`wc -l dirlist | awk '{print $1}'` echo -e "$numfiles files will be reordered\n" cat dirlist | while read i;	do (( --numfiles )) if ! -f $i ; then continue fi #We could be this paranoid but it would slow it down 1000 times #if `lsof -f -- "$i"` ; then #	echo -e "\n File $i open! Skipping" #	continue #fi filesize=`find "$i" -printf "%s"` # read the file first to cache it in ram if possible if (( filesize < maxsize )) then echo -e "\r $numfiles files left                             \c" cat "$i" > /dev/null else echo -e "\r $numfiles files left - Reordering large file sized $filesize ...       \c" fi datestamp=`find "$i" -printf "%s"` cp -a -f "$i" tmpfile if (( $? )) ; then fail fi # check the file hasn't been altered since we copied it		if `find "$i" -printf "%s"` != $datestamp  ; then continue fi mv -f tmpfile "$i" if (( $? )) ; then fail fi done echo -e "\nSucceeded" rm -f -- dirlist; }
 * 1) defrag v0.06 by Con Kolivas  /dev/null
 * 1) The maximum size of a file we can easily cache in ram
 * 1) Sort in the following order:
 * 2) 1) Depth of directory
 * 3) 2) Size of directory descending
 * 4) 3) Filesize descending
 * 1) stupid script to find max directory depth
 * 1) sort directories in descending size order
 * 1) sort files in descending size order
 * 1) copy to temp file, check the file hasn't changed and then overwrite original

alias dpkg="sudo dpkg --force-all"

if $SCREENP = True ; then alias debfoster="sudo screen -S "debfoster" debfoster" fi

function d { if [ $# -ne 1 ] then echo "usage: c pattern"; return fi set "foo" `egrep $1$ $HOME/.dload-dirs` if [ $# -eq 1 ] then echo "No matches"; elif [ $# -eq 2 ] then cd "$2"; ls; else shift for x in "$@"; do     echo $x done | nl -n ln   echo -n "Number: "; read C;   if [ "$C" = "0" -o -z "$C" ] then return fi   eval D="\${$C}"; if [ -n "$D" ] then cd "$D"; ls; fi fi  unset foo }
 * 1) dload finds and caches in the home directory a list of all directories.
 * 2) Then one requests to go to a directory like 'd bin' and it presents a numbered list - by typing a number
 * 3) you can go anywhere!

alias dload="rm -- ~/.dload-dirs; find / -type d >> ~/.dload-dirs"

alias add="darcs add" alias initialize="darcs initialize" alias whatsnew="darcs whatsnew" alias record="darcs record --verbose --ignore-times --author=gwern0@gmail.com" alias pull="darcs pull" alias get="darcs get"

alias dat="date +%_I:%M:%S%p--%e-%a"

alias defcon="defcon &"

function deletelines { sed -i -- "1,$2d" "$1"; }
 * 1) Remove the first n lines from a given file.

alias df="df -h" alias dub="du -sclb --" alias duk="du -sclk --" alias dum="du -sclm --" alias duh="du -sclh --" alias dfk="df -PTak --" alias dfm="df -PTam --" alias dfh="df -PTah --" alias dfi="df -PTai --"

alias dir="ls -al" #DOS compatibility

alias dhclient="sudo killall dhclient; sudo dhclient -e "

alias dmsg="dmesg | pg"

function du_extra { for dir in `find. -maxdepth 1 -type d`; do if [ $dir != "." ]		then echo "---"; du "$dir"; fi done echo "---"; }

alias e="${EDITOR}"

alias electric-sheep="sheep" if $SCREENP = True ; then alias sheep="screen -S "electric-sheep" -d -m electricsheep --nick `whoami` --frame-rate 10 --anim-only 1 --mplayer 1 --nice 19 --nrepeats 1 --reset-fuse 100 --zoom 1 --root 1" fi

alias eject="pushd . && cd && eject -v || sudo eject -v; popd"

alias emerg="sudo emerge"

alias env-update="sudo env-update"

function environment_validate { errors=0 in_path { # given a command and the PATH, try to find the command. Returns # 1 if found, 0 if not. Note that this temporarily modifies the # the IFS input field seperator, but restores it upon completion. cmd=$1 path=$2  retval=0 oldIFS=$IFS; IFS=":" for directory in $path do if [ -x $directory/$cmd ] then retval=1;  # if we're here, we found $cmd in $directory fi done IFS=$oldIFS return $retval } validate {		varname=$1 varvalue=$2 if [ ! -z $varvalue ] then if [ "${varvalue%${varvalue#?}}" = "/" ] then if [ ! -x $varvalue ] then echo "** $varname set to $varvalue, but I cannot find executable."; errors=$(( $errors + 1 )); fi else if in_path $varvalue $PATH then echo "** $varname set to $varvalue, but I cannot find it in PATH." errors=$(( $errors + 1 )) fi fi fi } if [ ! -x ${SHELL:?"Cannot proceed without SHELL being defined."} ] then echo "** SHELL set to $SHELL, but I cannot find that executable."; errors=$(( $errors + 1 )); fi if [ ! -d ${HOME:?"You need to have your HOME set to your home directory"} ] then echo "** HOME set to $HOME, but it's not a directory." errors=$(( $errors + 1 )) fi oldIFS=$IFS; IFS=":"   # IFS is the field separator. We'll change to ':' for directory in $PATH do if [ ! -d $directory ] then echo "** PATH contains invalid directory $directory"; errors=$(( $errors + 1 )) fi done IFS=$oldIFS      # restore value for rest of script validate "EDITOR" $EDITOR validate "MAILER" $MAILER validate "PAGER" $PAGER if [ $errors -gt 0 ] then echo "Errors encountered. Please notify sysadmin for help."; else echo "Your environment checks out fine."; fi }
 * 1) Thanks to "Wicked Cool Shell Scripts: 101 Scripts for Linux, Mac OS X, and Unix Systems"
 * 1) !/bin/sh
 * 2) VALIDATOR - Checks to ensure that all environment variables are valid
 * 3)  looks at SHELL, HOME, PATH, EDITOR, MAIL, and PAGER
 * 1) Beginning of actual shell script #######
 * 1) Our first interesting test: are all the paths in PATH valid?
 * 1) The following can be undefined, and they can also be a progname, rather
 * 2) than a fully qualified path. Add additional variables as necessary for
 * 3) your site and user community.
 * 1) and, finally, a different ending depending on whether errors > 0

alias emacs="enw" alias enw="emacs -nw"
 * 1) Let's try using Emacs from the terminal for a while.

alias eselect="sudo eselect"

alias etc-update="sudo etc-update" alias etcupdate="etc-update"

function fe { /usr/bin/feh -FD10 -F --zoom --auto-zoom -A "rm %f" -- *.png & } function feh { /usr/bin/feh -FD10 -F --zoom --auto-zoom -A "rm %f" -- *.jpg & }
 * 1) Using functions rather than aliases to avoid format problems and naming clashes.
 * 2) There must be a better way besides hardwiring things.

alias fetch="torify fetchmail -v -m \"/usr/bin/procmail -d %T\""

alias file="file -k -p -z --"

alias findhog="du -ks * | sort -nr"

function findsuid { mtime="7"	# how far back (in days) to check for modified cmds verbose=1	# by default, let's be quiet about things if [ "$1" = "-v" ] then verbose=1; fi for match in $(find /bin /usr/bin -type f -perm +4000 -print) do		if [ -x $match ] then owner="$(ls -ld $match | awk '{print $3}')"; perms="$(ls -ld $match | cut -c5-10 | grep 'w')"; if [ ! -z $perms ] then echo "**** $match (writeable and setuid $owner)"; elif [ ! -z $(find $match -mtime -$mtime -print) ] then echo "**** $match (modified within $mtime days and setuid $owner)"; elif [ $verbose -eq 1 ] then lastmod="$(ls -ld $match | awk '{print $6, $7, $8}')"; echo "  $match (setuid $owner, last modified $lastmod)"; fi fi done }
 * 1) Thanks to "Wicked Cool Shell Scripts: 101 Scripts for Linux, Mac OS X, and Unix Systems"
 * 1) !/bin/sh
 * 2) findsuid - find all SUID files or programs on the system other than those
 * 3) that live in /bin and /usr/bin, and output the matches in a useful format.

alias firefox-prelink="sudo prelink --random --black-list /home -q --verbose --ld-library-path=/usr/lib/firefox/ --conserve-memory --libs-only /usr/lib/firefox/ && sudo /usr/sbin/prelink --random --black-list /home -q --verbose --ld-library-path=/usr/lib/firefox/ --conserve-memory /usr/lib/firefox --"

alias fmt="space -- *; lower -- *; brackets -- *; characters -- * &"

function brackets { for file in "$@" do		mv "$1" `echo "$1" | tr --delete '' | tr --delete '[,]'` 2>/dev/null; shift; done; }

function characters { for file in "$@" do new=`echo "$1" | tr --delete \" |tr --delete \' | tr --delete '~' | tr --delete '/,\' | tr --delete [:cntrl:] | tr --delete [:blank:] | tr --delete [:space:] | tr --delete '&' | tr --delete \! | tr --delete \# | tr --delete \;`;		mv "$1" $new 2>/dev/null;		shift; done; }

function lower { for file in "$@" do		mv "$1" `echo "$1" | tr [:upper:] [:lower:] | tr --delete /` 2>/dev/null; shift; done; }

function space { for file in "$@"; do		mv "$1" "${file// /-}" 2>/dev/null; shift; done; }

alias fortune="nice fortune -a &"

export GREP_COLOR=31 alias grep='grep --color=auto' alias g="grep"
 * 1) Color grepping, yay!

alias ghci="ghci -v -Wall -fglasgow-exts" alias ghc="ghc -v -Wall -fglasgow-exts -O2"

if `which ghc >/dev/null` then function hmap { ghc -e "interact ($*)"; } function hmapl { hmap "unlines.($*).lines" ; } function hmapw { hmapl "map (unwords.($*).words)" ; } fi

alias gq="gqview -t &" alias gqv="gqview" alias gqview="gqview"

alias h="history"

alias help="man"

alias hibernate="sudo hibernate --kill --verbosity=3"

alias hml2txt="html2text -ascii -nobs -style pretty --" alias h2t="html2txt"

alias ifconfig="sudo ifconfig"

alias ii="this_ip 2>&-; echo -e '\nYou are logged on ${RED}$HOSTNAME${NCOL} ( `echo ${THIS_IP:-\'Not connected\'}` )'; echo -e '\n${RED}Additional information:${NCOL} '; uname -a; echo -e '\n${RED}Users logged on:${NCOL} '; w -h; echo -e '\n${RED}Current date :${NCOL} '; date; echo -e '\n${RED}Machine stats :${NCOL} '; uptime;echo -e '\n${RED}Memory stats :${NCOL} '; free"

alias irc="irssi"
 * 1) currently irssi is my IRC client

if $SCREENP = True ; then function irssi { if [ -n "$(screen -list | grep irssi)" ] then screen -wipe; screen -raAdO irssi else killall irssi; if -n `which torify` then screen -O -S "irssi" torify irssi --nick=$USER; ls; else screen -O -S "irssi" irssi --connect=irc.freenode.net --nick=$USER; ls; fi fi } fi
 * 1) Alias for irssi IRC client. First, get a list of running screens from screen, then grep it for the string 'irssi'
 * 2) If irssi is not running, then run irssi in a screen

alias jc="javac -verbose -g -deprecation *.java" alias j="java"

alias kernfs="pg /proc/filesystems"

alias l="ls -q --color=auto" #This isn't visible in functions. alias la="ls --color=auto -AFq --" alias ll="find . -maxdepth 1 -user `whoami` ! -type d -ls -execdir file -b '{}' \;;"

alias ls="ls --color=auto --file-type" alias lsd="ls --color=auto -d ./*/ --"

alias layman="sudo layman"

alias length="wc -m --"

alias line-fmt="line_format" function line_format { while getopts "hw:" opt; do		case $opt in			h) hyph=1       ;;			w) width="$OPTARG"   ;; esac done shift $(($OPTIND - 1)) nroff << EOF .ll ${width:-72} .na .hy ${hyph:-0} .pl 1 $(cat "$@") EOF }
 * 1) Thanks to "Wicked Cool Shell Scripts: 101 Scripts for Linux, Mac OS X, and Unix Systems"
 * 1) !/bin/sh
 * 2) A version of fmt, using nroff. Adds two useful flags: -w X for line width
 * 3)  and -h to enable hyphenation for better fills.

alias load="uptime | cut -d ' ' -f 9- --" #extract the system load information from uptime

alias logout="clear & sync && logout"

alias md="mkd" alias mkd="mkdir -p" alias mkdirs="mkd"

alias mvd="mv"

function miso { mount -t iso9660 -o ro,loop -- "$@" /mnt/iso; } alias umiso="umount -- /mnt/iso"

alias mk="make"

alias mp="mplayer -framedrop -nojoystick -nolirc -nocache -idx -identify -cache 8192 -cache-min 2" if $SCREENP = True ; then function m { screen -S "mplayer" mplayer -hardframedrop -nojoystick -nolirc -nocache -idx -identify -autosync 30 -vf scale -cache 8192 -cache-min 2 -- "$@"; ls --color=auto ./; } else #use a normal alias alias m="mp" fi
 * 1) Base configuration for mplayer.
 * 1) If screen is available, use it

alias modprobe="sudo modprobe"

alias more="pager"
 * 1) less is more. :)

alias mount="sudo mount"

alias move="mv"

if $SCREENP = True ; then alias mp32ogg="screen -S "mp32ogg" nice mp32ogg --delete -- *.mp3" else alias mp32ogg="nice mp32ogg --delete" fi

alias mvsget="mvs update [^.]*.wiki" #Exclude anything starting with '.', include all ending with '.wiki' alias mvs_login="mvs login -d wikipedia.org -l en -u User:$USER; mvsget"

alias mvscommit="mvsget; mvs commit -m"

alias n="nano"

if $SCREENP = True ; then alias normalize-ogg="screen -S "normalize" nice normalize-ogg --ogg -v -- *.ogg" fi

if $SCREENP = True ; then alias oggdec="screen -S "oggdec" nice oggdec -- *.ogg && l" alias oggenc="screen -S "oggenc" nice oggenc -q 10 -- *.wav && rm -- *.wav && l" fi

alias openoffice="ooffice"

alias optipng="nice optipng -o9 -fix"

alias p="pager" function pager { #first, let's handle the case of stuff being piped here. if [ $# = 0 ] #If there are no arguments, then just run less on stdin then less --; else for argument in "$@"; #loop over arguments do length=`ls -s "$1" | cut -d " " -f 1` if $((length > 4)) = 1  #0 is false, 1 is true; the 4 is a heuristic then less "$1"; #If it is too long, then...

else if grep ".bz\|.gz\|.bz2"` #we need to know whether it is compressed. less can handle compressed. then less "$1"; else cat "$1"; #If it is short, than cat suffices. fi fi shift; done; fi }

alias recurse_picture="picture_convert" alias picture_convert="(picture_convert_to_png &)" function picture_convert_to_png { for directory in `find. -name "*.jpg" -exec dirname "{}" \; | sort | uniq` do	 pushd .; cd $directory; fmt popd; done
 * 1) Recurse down from current directory, convert everything to png, and optimize.
 * 2) Current bugs: doesn't delete converted files.
 * 3) find . -name "*.jpg" -execdir echo {} \; | sed 's/\.[^.]*$//'

find. -name "*.jpg" -exec sh -c "convert -- {} {}.png && rm -- {} " \;; find. -name "*.jpeg" -exec sh -c "convert -- {} {}.png && rm -- {} " \;; find. -name "*.gif" -exec sh -c "convert -- {} {}.png && rm -- {} " \;; find. -name "*.bmp" -exec sh -c "convert -- {} {}.png && rm -- {} " \;; find. "*.png" -mmin -500 -exec nice optipng -o9 -- {} +;

for file in `find. -name "*.jpg.png"` do   # remove everything starting with last '.' base=`echo "$file" | sed 's/\.[^.]*$//' | sed 's/\.[^.]*$//'`; mv -- $file $base.png; done }

alias path='echo "$PATH"'
 * 1) Display current $PATH variable:

alias pg="pager"

alias ping="sudo nice ping -A -l 5 -c 1000 --"

alias plan="$EDITOR .plan"

alias privoxy="sudo privoxy /etc/privoxy/config"

alias py="python -O -O -t"

if $SCREENP = True then alias prelink="sudo screen -S "prelink" prelink --all -m --dereference --no-exec-shield" else alias prelink="prelink --all -m --dereference --no-exec-shield" fi

alias preload="sudo preload --nice -19"

function printdir { gmk {		if [ $1 -ge 1000000 ] then echo "$(scriptbc -p 2 $1 / 1000000)Gb"; elif [ $1 -ge 1000 ] then echo "$(scriptbc -p 2 $1 / 1000)Mb"; else echo "${1}Kb" fi }
 * 1) Thanks to "Wicked Cool Shell Scripts: 101 Scripts for Linux, Mac OS X, and Unix Systems"
 * 1) !/bin/sh
 * 2) formatdir - output a directory listing in a friendly and useful format
 * 1) given input in Kb, output in Kb, Mb or Gb for best output format

dir=`pwd` #save our spot

if [ $# -gt 1 ] then echo "Usage: $0 [dirname]" >&2; elif [ $# -eq 1 ] then cd -- "$@"; fi

for file in * do   if [ -d "$file" ] then size=$(l -d "$file" | wc -l | sed 's/[^[:digit:]]//g'); if [ $size -eq 1 ] then echo "$file ($size entry)|"; else echo "$file ($size entries)|"; fi   else size="$(l -dsk "$file" | awk '{print $1}')"; echo "$file ($(gmk $size))|"; fi done | \ sed 's/ /^^^/g' | \ xargs --max-procs=0 -n 2  | \ sed 's/\^\^\^/ /g' | \ awk -F\| '{ printf "%-39s %-39s\n", $1, $2 }'

cd $dir; }

alias random_picture="random_picture_on_root &" function random_picture_on_root { cd ~/pics; #where we store pictures. files=(*.png);       # Or *.gif, or * n=${#files[@]};      # For aesthetics random="${files[RANDOM %n]}" # Choose a random element xsetbg -border black -fork -brighten 60 -type png -fit -onroot -fullscreen $random } #'
 * 1) Use xsetbg to select a random file from one's picture directory and set it as the root window.
 * 2) This is copied in .xinitrc

alias ps="ps -A -j -H v"

alias q="exit; logout"

alias revdep-rebuild="sudo revdep-rebuild -v -X -i"

alias rc-update="sudo rc-update"

for service in `cd /etc/init.d/; ls` do alias "rc-${service}"="/etc/init.d/${service}" done
 * 1) Create rc-foo shortcuts rather than lengthy /etc/init.d/ stuff.
 * 2) Is it efficient for this to be here?

alias reboot="sudo nice reboot -n -i -h; sync & logout"

function rmd  { if [ -d "$1" ] #remove only directories! then rm --force --recursive --verbose -- "$@"; ls --color=auto; else echo "$@" "is not a directory"; fi shift #we've deleted the first argument, so scrap it     #and let's process the next argument. if [ $# -eq 1 ] #if there are no more arguments, we will #quietly end the function. then rmd "$@"; fi; } alias rm="rm -v"
 * 1) Remove a directory and contents; handles multiple arguments

alias root-tail='sudo root-tail'

if $SCREENP = True ; then alias rtorrent="(rtorrent_unsafe)" function rtorrent_unsafe { if [ -n "$(screen -list | grep rtorrent)" ] then screen -wipe; screen -raAdO rtorrent; else killall rtorrent; mv *.torrent ~/torrent/; cd ~/torrent/; http_proxy="" screen -S "rtorrent" nice rtorrent -- *.torrent; ls; fi } fi

alias s="screen -O"

alias sbcl="sbcl --noinform --dynamic-space-size 42 -eval '(declare (optimize (speed 3) (safety 0) (space 3) (compilation-speed 0)))'"

function scriptbc {
 * 1) Thanks to "Wicked Cool Shell Scripts: 101 Scripts for Linux, Mac OS X, and Unix Systems"
 * 1) !/bin/sh
 * 2) scriptbc - wrapper for 'bc' that returns the value of a formula

if [ $1 = "-p" ] ; then precision=$2 shift 2 else precision=2		# default fi

bc -q -l << EOF scale=$precision $* quit EOF } alias shutdown="sudo nice shutdown now"

if -n `which torify` ; then function ssh { unset cmd cmd="ssh" while [ -n "${1}" ] ; do			if [ "${1:0:1}" == "-" ] ; then found=0 for white in -1 -2 -4 -6 -A -a -C -f -g \ -k -N -n -q -s -T -t -V -v -X -x \ -Y \ ; do					[ "${1}" == "${white}" ] && found=1 done if [ "${found}" == "0" ] ; then cmd="${cmd} \"${1}\" \"${2}\"" shift # the second shift happens below else cmd="${cmd} \"${1}\"" fi else if [ "${1//@}" != "${1}" ] ; then cmd="${cmd} \"${1%%@*}@"					ip="$(tor_resolve "${1##*@}")"					cmd="${cmd}${ip}\"" else ip="$(tor_resolve "${1}")" cmd="${cmd} \"${ip}\"" fi fi shift done eval torify ${cmd} } function scp { unset cmd cmd="scp" while [ -n "${1}" ] ; do			if [ "${1:0:1}" == "-" ] ; then for white in -1 -2 -4 -6 -B -C -p -q -r -v \ ; do					[ "${1}" == "${white}" ] && found=1 done if [ "${found}" == "0" ] ; then cmd="${cmd} \"${1}\" \"${2}\"" shift # the second shift happens below else cmd="${cmd} \"${1}\"" fi else if [ "${1//:}" != "${1}" ] ; then cmd="${cmd} \""					host="${1}"					if [ "${1//@}" != "${1}" ] ; then						cmd="${cmd}${1%%@*}@"						host="${1#*@}"					fi					ip="$(tor_resolve "${host%%:*}")"					cmd="${cmd}${ip}:${host#*:}\"" else cmd="${cmd} \"${1}\"" fi fi shift done eval torify ${cmd} } fi alias shred="shred -n 31337 -z -u"
 * 1) Following complex TOR-stuff from the Tor aliases project.

if -n `which torify` ; then alias svn="torify svn" fi
 * 1) subversion

alias sud="sudo"

alias t="typo"

function this_ip { THIS_IP=$(/sbin/ifconfig eth0 | awk '/inet/ { print $2 } ' | sed -e s/addr://) }

alias top="nice top -c -d 1.5 --"

alias tor="sudo tor"

function tor_resolve { if egrep -q "blank:${1}|blank:${1}blank:" /etc/hosts ; then echo "${1}" return 0 else echo -n "Resolving ${1} through tor... " >&2 ip="$( tor-resolve ${1} 2>/dev/null )" if [ -z "${ip}" ] ; then echo "FAILED! Passing ${1} to program" >&2; echo ${1}; return 1 else echo ${ip} >&2; echo ${ip}; return 0 fi; fi }
 * 1) This function first tries /etc/hosts for the name
 * 2) then tries tor. echos either the parameter or the IP address
 * 3) return value 0 for success (resolved or hosts), 1 otherwise

alias tgz='tar -cvvzf' alias tbz2='tar -cvvjf' alias mktar='tar -cvvf' alias untar='tar -xvvf' alias utgz='tar -xvvzf' alias utbz2='tar -xvvjf'

function typo { (typo_unsafe "$@"); alias $1=$2; } function typo_unsafe { cd; #we need to be in a repository directory, which is ~/ echo alias $1='"'$2'"' >> ~/.bashrc; #It goes typo wrong-command right-command tail -n 1 ~/.bashrc; #Verify that bashrc was written, with the right thing. $2; record --skip-long-comment --all --patch-name="alias $1="$2""; }
 * 1) So often I make little stupid typos while firing away
 * 2) in the shell. They are very annoying, but it is too
 * 3) much trouble to fire up Emacs or nano to manually
 * 4) add an alias that would fix the problem. And typing
 * 5) the appropriate echo and append command is tedious and
 * 6) error prone. So, I whipped up a quick shell script which
 * 7) reads the two arguments provided, and constructs the appropriate
 * 8) echo command to create an alias that solves that typo.

alias umount="sudo umount" alias unmount="sudo umount"

alias rar="unrar x"

alias xmon="(xmonad_upgrade)" alias xmonad_upgrade="cd ~/bin/xmonad/; darcs pull -a; runhaskell Setup configure --user --prefix=$HOME && runhaskell Setup build && ln -sf $PWD/dist/build/xmonad/xmonad $HOME/bin/xmonad-bin"

if $SCREENP = True ; then alias updatedb="screen -S "updatedb" sudo nice updatedb" else alias updatedb="sudo nice updatedb" fi

if $SCREENP = True then alias visualboy="screen -S "gba" VisualBoyAdvance --rtc" else alias visualboy="VisualBoyAdvance --rtc" fi alias gba="visualboy" alias visualboyadvance="visualboy" alias VisualBoy="visualboy"

function warnswap { min_space=100 swap_free=$(free -mo | grep Swap | { read a b c d; echo $d; })

if (( $swap_free < $min_space )) then echo -e \\a Swap is running low! Less then ${1}Mb left. fi }
 * 1) write message to terminal and ring a bell

if $SCREENP = True ; then alias wget="screen -S "wget" nice wget" fi

function wmaconvert { #Convert all the WMA files to wav in a loop, then delete the WMA #and encode the wavs to oggs. for file in *.wma do   nice mplayer -vc null -vo null -ao pcm:fast -- `echo "$file" | tr .wma .wav` "$file"; mv -- audiodump.wav `echo "$file" | tr .wma .wav`; echo "$file"; done rm -- *.wma; #remove the old WMAs only after all conversions finish succcessfully.

oggenc; #All the WMAs are now gone. Turn things over to oggenc. }

alias x="pushd .; startx -- -layout XineramaLayout; popd"

alias xargs="xargs --max-procs=0"

function xpdf { `which xpdf` "$@" & }

alias z="suspend"

if $SCREENP = True ; then function disambig_pywikipedia { pywikipedia_update && cd ~/bin/pywikipedia; http_proxy="" HTTP_PROXY="" screen -O -S "disambig" python solve_disambiguation.py -main -- "$@"; } alias disambig="(disambig_pywikipedia)" fi
 * 1) Pywikipediabot
 * 1) Pywikipediabot

if $SCREENP = True ; then function followlive_pywikipedia { pywikipedia_update && cd ~/bin/pywikipedia && HTTP_PROXY="" http_proxy="" screen -S "followlive" nice python followlive.py; } else alias followlive_pywikipedia="cd ~/bin/pywikipedia && python followlive.py" fi alias followlive="(followlive_pywikipedia)"

if $SCREENP = True ; then alias checker="(pywikipedia_checker)" function pywikipedia_checker { #now let's define the function alpha="abcdefghijklmnopqrstuvwxyz" if [ -n "$(screen -list | grep link-checker)" ]; then screen -wipe; screen -raAdO link-checker; else pywikipedia_update; cd ~/bin/pywikipedia/ && screen -O -S "link-checker" sh -c 'while true; do http_proxy="" HTTP_PROXY="" nice -n 19 python weblinkchecker.py -start:${alpha:RANDOM%26:1}; done;' fi } else alias checker="cd ~/bin/pywikipedia/ && nice python weblinkchecker.py -start:F;" fi

echo "Logged in on $(tty), as $(whoami) in directory $(pwd)."; ls;
 * 1) Commands run on startup #
 * 1) Commands run on startup #

declare -x SURFRAW_debian_release="all" declare -x SURFRAW_debian_distro="all"
 * 1) Surfraw stuff
 * 2) Added by surfraw. To remove use surfraw-update-path -remove
 * 3) Surfraw environment variables
 * 1) End surfraw addition.

alias ,,=".." alias 1killall="killall" alias 3m="m" alias 8irss="irssi" alias ano="nano" alias atsnew="whatsnew" alias ca="cat" alias cat="ca" alias ~c="c" alias C="c" alias conver="convert" alias convrt="convert" alias dacs="darcs" alias da="darcs" alias darc="darcs" alias dff="df" alias disambi="disambig" alias emcs="emacs" alias emrege="emerge" alias emrge="emerge" alias feg="feh" alias fetchmai="fetchmail" alias finmdhog="findhog" alias ~fmt="fmt" alias freee="free" alias ghic="ghci" alias gunzup="gunzip" alias h2txt="h2t" alias hci="ghci" alias hdparm="sudo hdparm" alias i9rssirss="irssi" alias ifconfige="ifconfig" alias imrar="unrar" alias inrar="unrar" alias instal="install" alias intall="install" alias iorss="irssi" alias ipgrade="upgrade" alias irs="irssi" alias irss="irssi" alias irsss="irssi" alias isntall="install" alias iurss="irssi" alias kiall="killall" alias kiillall="killlall" alias kilall="killall" alias kilalll="killall" alias kil="kill" alias killlall="killall" alias klillall="killall" alias ks="ls" alias les="less" alias link_0c="link_checker" alias link_c="link_checker" alias link_="link_checker" alias lionk_checker="link_checker" alias lmutt="mutt" alias loate="locate" alias locat="locate" alias ~ls="ls" alias lsw="ls" alias lw="ls" alias lynx="elinks" alias md5="md5sum" alias mitt="mutt" alias mkdr="mkdir" alias mmv="mv" alias mna="man" alias mn="man" alias mplaer="mplayer" alias mplater="mplayer" alias mplauyer="mplayer" alias mplyaer="mplayer" alias mqake="make" alias mu="mutt" alias mut="mutt" alias ~mutt="mutt" alias muut="mutt" alias naon="nano" alias natilus="nautilus" alias nautlius="natilus" alias ncie="nice" alias nv="mv" alias oo="ooffice" alias ooptpng="optipng" alias opitpng="optipng" alias op="top" alias orss="irssi" alias os="ps" alias oython="python" alias pa="ps" alias pdf2text="pdftotext" alias pdf="xpdf" alias piing="ping" alias pkg="dpkg" alias podf="pdf" alias pps="ps" alias psps="ps" alias pt_get="apt-get" alias pushd.="pushd ." alias pythong="python" alias rboot="reboot" alias recored="record" alias recor="record" alias recrd="record" alias remopve="remove" alias restart="reboot" alias revert="darcs revert" alias rexord="record" alias rirss="irssi" alias rmdd="rmd" alias rmds="rmd" alias rmeove="remove" alias r,m="rm" alias rotorrent="rtorrent" alias rotrrent="rtorrent" alias rrebnoot="reboot" alias rrm="rm" alias rtorr="rtorrent" alias rtor="rtorrent" alias rtprrent="rtorrent" alias rtrorrent="rtorrent" alias sarch="search" alias screeen="screen" alias scree="screen" alias seach="search" alias seaerch="search" alias searcg="search" alias searcj="search" alias searhc="search" alias searh="search" alias sear="search" alias searxh="search" alias seearch="search" alias serch="search" alias sgow="show" alias sheeo="sheep" alias shiow="show" alias showv="show" alias shsheep="sheep" alias shw="show" alias sl="ls" alias sreen="screen" alias sudedit="sudoedit" alias sudeodit="sudoedit" alias sudochmod="sudo chmod" alias sudodit="sudoedit" alias sudoedi="sudoedit" alias sudoeit="sudoedit" alias sudoiedt="sudoedit" alias sudpedot="sudoedit" alias sudp="sudo" alias sydoedit="sudoedit" alias sydo="sudo" alias tiop="top" alias tio="top" alias toop="top" alias top]="top" alias to="top" alias tpo="top" alias tp="top" alias ttop="top" alias tup="top" alias tyo="typo" alias typoe="typo" alias typpo="typo" alias udoedit="sudoedit" alias udo="sudo" alias udpdate="update" alias ugrade="upgrade" alias ]umount="umount" alias unarar="unrar" alias unar="unrar" alias unIp="unzip" alias unraru="unrar" alias unsip="unzip" alias unxip="unzip" alias unziop="unzip" alias unzipo="unzip" alias unzi="unzip" alias unziup="unzip" alias unzoip="unzip" alias unzp="unzip" alias unzuip="unzip" alias unzuo="unzip" alias unzup="unzip" alias uograde="upgrade" alias upgdare="upgrade" alias upgradew="upgrade" alias upgradfe="upgrade" alias upgrad="upgrade" alias upgradwe="upgrade" alias upgrde="upgrade" alias upgr="upgrade" alias uphrade="upgrade" alias uprade="upgrade" alias uptume="uptime" alias utnar="untar" alias uttt="mut" alias uzip="unzip" alias uznip="unzip" alias whastnew="whatsnew" alias whgatsnew="whatsnew" alias whjatsnew="whatsnew" alias whtsnew="whatsnew" alias ~wine="wine" alias wtop="top" alias xmonad_update="xmonad_upgrade" alias xmonad_up="xmonad_upgrade" alias xmonad_="xmonad_upgrade" alias xmond_update="xmonad_update" alias xmon_="xmonad_upgrade" alias xterm="urxvt" alias x~="x" alias xxpdf="xpdf" alias ymutt="mutt" alias findho0g="findhog" alias touc="touch" alias emac="emacs" alias enacs="emacs" alias sea="search" alias seaa="search" alias ekject="eject" alias shread="shred" alias equeryy="equery" alias 4mutt="mutt" alias emrg="emerg" alias muttt="mutt" alias mmutmutt="mutt" alias runhaskel="runhaskell" alias xnon="xmon"
 * 1) Typo aliases.