Guest User

ultimate bashrc

a guest
Jan 16th, 2011
6,145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 346.58 KB | None | 0 0
  1. ######################################################################################################################################################
  2. ################################### MY BASHRC FILE ################################### MY BASHRC FILE ################################### MY BASHRC FILE
  3. ######################################################################################################################################################
  4.  
  5.  
  6.  
  7.  
  8.  
  9.  
  10.  
  11.  
  12. # .bashrc
  13. # Creator:  inameiname
  14. # Version:  2.91
  15. # Last modified: 13 January 2011
  16. # Found through various sources (including several things by me)
  17. # Commented out stuff is what I personally don't need,
  18. # so use at your own risk
  19. # Feel free to copy, share, tweak, eat, or whatever
  20.  
  21.  
  22.  
  23.  
  24.  
  25.  
  26.  
  27.  
  28. ######################################################################################################################################################
  29. #----- ORIGINAL CONTENT ------ ORIGINAL CONTENT ------ ORIGINAL CONTENT ------ ORIGINAL CONTENT ------ ORIGINAL CONTENT ------ ORIGINAL CONTENT ------
  30. ######################################################################################################################################################
  31.  
  32.  
  33.  
  34.  
  35.  
  36.  
  37.  
  38.  
  39. # ~/.bashrc: executed by bash(1) for non-login shells.
  40. # see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
  41. # for examples
  42.  
  43. # If not running interactively, don't do anything
  44. [ -z "$PS1" ] && return
  45.  
  46. # don't put duplicate lines in the history. See bash(1) for more options
  47. # ... or force ignoredups and ignorespace
  48. HISTCONTROL=ignoredups:ignorespace
  49.  
  50. # append to the history file, don't overwrite it
  51. shopt -s histappend
  52.  
  53. # for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
  54. HISTSIZE=1000
  55. HISTFILESIZE=2000
  56.  
  57. # check the window size after each command and, if necessary,
  58. # update the values of LINES and COLUMNS.
  59. shopt -s checkwinsize
  60.  
  61. # make less more friendly for non-text input files, see lesspipe(1)
  62. [ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"
  63.  
  64. # set variable identifying the chroot you work in (used in the prompt below)
  65. if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then
  66.     debian_chroot=$(cat /etc/debian_chroot)
  67. fi
  68.  
  69. # set a fancy prompt (non-color, unless we know we "want" color)
  70. case "$TERM" in
  71.     xterm-color) color_prompt=yes;;
  72. esac
  73.  
  74. # uncomment for a colored prompt, if the terminal has the capability; turned
  75. # off by default to not distract the user: the focus in a terminal window
  76. # should be on the output of commands, not on the prompt
  77. # force_color_prompt=yes
  78.  
  79. if [ -n "$force_color_prompt" ]; then
  80.     if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
  81.     # We have color support; assume it's compliant with Ecma-48
  82.     # (ISO/IEC-6429). (Lack of such support is extremely rare, and such
  83.     # a case would tend to support setf rather than setaf.)
  84.     color_prompt=yes
  85.     else
  86.     color_prompt=
  87.     fi
  88. fi
  89.  
  90. if [ "$color_prompt" = yes ]; then
  91.     PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
  92. else
  93.     PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
  94. fi
  95. unset color_prompt force_color_prompt
  96.  
  97. # If this is an xterm set the title to user@host:dir
  98. case "$TERM" in
  99. xterm*|rxvt*)
  100.     PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
  101.     ;;
  102. *)
  103.     ;;
  104. esac
  105.  
  106. # enable color support of ls and also add handy aliases
  107. if [ -x /usr/bin/dircolors ]; then
  108.     test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
  109.     alias ls='ls --color=auto'
  110.     # alias dir='dir --color=auto'
  111.     # alias vdir='vdir --color=auto'
  112.  
  113.     alias grep='grep --color=auto'
  114.     alias fgrep='fgrep --color=auto'
  115.     alias egrep='egrep --color=auto'
  116. fi
  117.  
  118. # some more ls aliases
  119. alias ll='ls -alF'
  120. alias la='ls -A'
  121. alias l='ls -CF'
  122.  
  123. # Add an "alert" alias for long running commands.  Use like so:
  124. #   sleep 10; alert
  125. 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$//'\'')"'
  126.  
  127. # Alias definitions.
  128. # You may want to put all your additions into a separate file like
  129. # ~/.bash_aliases, instead of adding them here directly.
  130. # See /usr/share/doc/bash-doc/examples in the bash-doc package.
  131.  
  132. if [ -f ~/.bash_aliases ]; then
  133.     . ~/.bash_aliases
  134. fi
  135.  
  136. # enable programmable completion features (you don't need to enable
  137. # this, if it's already enabled in /etc/bash.bashrc and /etc/profile
  138. # sources /etc/bash.bashrc).
  139. if [ -f /etc/bash_completion ] && ! shopt -oq posix; then
  140.     . /etc/bash_completion
  141. fi
  142.  
  143.  
  144.  
  145.  
  146.  
  147.  
  148.  
  149.  
  150. ######################################################################################################################################################
  151. #----- CUSTOM STARTS HERE ------ CUSTOM STARTS HERE ------ CUSTOM STARTS HERE ------ CUSTOM STARTS HERE ------ CUSTOM STARTS HERE ------ CUSTOM STARTS HERE
  152. ######################################################################################################################################################
  153.  
  154.  
  155.  
  156.  
  157.  
  158.  
  159.  
  160.  
  161. ######################################################################################################################################################
  162. ###### MISCELLANEOUS ###### MISCELLANEOUS ###### MISCELLANEOUS ###### MISCELLANEOUS ###### MISCELLANEOUS ###### MISCELLANEOUS ###### MISCELLANEOUS ######
  163. ######################################################################################################################################################
  164.  
  165.  
  166.  
  167.  
  168.  
  169.  
  170.  
  171.  
  172. if [ "$PS1" ]; then # if running interactively, then run till 'fi' at EOF:
  173.  
  174. # source ~/.bashlocalrc # settings that vary per workstation
  175. OS=$(uname)     # for resolving pesky os differing switches
  176.  
  177.  
  178.  
  179.  
  180.  
  181.  
  182.  
  183.  
  184. ######################################################################################################################################################
  185. ###### COMMAND PROMPT & CLI ###### COMMAND PROMPT & CLI ###### COMMAND PROMPT & CLI ###### COMMAND PROMPT & CLI ###### COMMAND PROMPT & CLI ######
  186. ######################################################################################################################################################
  187.  
  188.  
  189.  
  190.  
  191.  
  192.  
  193.  
  194.  
  195. ##################################################
  196. # Prompt escapes                 #
  197. ##################################################
  198.  
  199. # Bash allows these prompt strings to be customized by inserting a
  200. # number of backslash-escaped special characters that are
  201. # decoded as follows:
  202.  
  203. #  \a         an ASCII bell character (07)
  204. #  \d         the date in "Weekday Month Date" format (e.g., "Tue May 26")
  205. #  \D{format} the format is passed to strftime(3) and the result
  206. #             is inserted into the prompt string an empty format
  207. #             results in a locale-specific time representation.
  208. #             The braces are required
  209. #  \e         an ASCII escape character (033)
  210. #  \h         the hostname up to the first `.'
  211. #  \H         the hostname
  212. #  \j         the number of jobs currently managed by the shell
  213. #  \l         the basename of the shell's terminal device name
  214. #  \n         newline
  215. #  \r         carriage return
  216. #  \s         the name of the shell, the basename of $0 (the portion following
  217. #             the final slash)
  218. #  \t         the current time in 24-hour HH:MM:SS format
  219. #  \T         the current time in 12-hour HH:MM:SS format
  220. #  \@         the current time in 12-hour am/pm format
  221. #  \A         the current time in 24-hour HH:MM format
  222. #  \u         the username of the current user
  223. #  \v         the version of bash (e.g., 2.00)
  224. #  \V         the release of bash, version + patch level (e.g., 2.00.0)
  225. #  \w         the current working directory, with $HOME abbreviated with a tilde
  226. #  \W         the basename of the current working directory, with $HOME
  227. #             abbreviated with a tilde
  228. #  \!         the history number of this command
  229. #  \#         the command number of this command
  230. #  \$         if the effective UID is 0, a #, otherwise a $
  231. #  \nnn       the character corresponding to the octal number nnn
  232. #  \\         a backslash
  233. #  \[         begin a sequence of non-printing characters, which could be used
  234. #             to embed a terminal control sequence into the prompt
  235. #  \]         end a sequence of non-printing characters
  236. #
  237. #  The command number and the history number are usually different:
  238. #  the history number of a command is its position in the history
  239. #  list, which may include commands restored from the history file
  240. #  (see HISTORY below), while the command number is the position in
  241. #  the sequence of commands executed during the current shell session.
  242. #  After the string is decoded, it is expanded via parameter
  243. #  expansion, command substitution, arithmetic expansion, and quote
  244. #  removal, subject to the value of the promptvars shell option (see
  245. #  the description of the shopt command under SHELL BUILTIN COMMANDS
  246. #  below).
  247.  
  248.  
  249.  
  250. ##################################################
  251. # Color chart                    #
  252. ##################################################
  253.  
  254. txtblk='\e[0;30m' # Black - Regular
  255. txtred='\e[0;31m' # Red
  256. txtgrn='\e[0;32m' # Green
  257. txtylw='\e[0;33m' # Yellow
  258. txtblu='\e[0;34m' # Blue
  259. txtpur='\e[0;35m' # Purple
  260. txtcyn='\e[0;36m' # Cyan
  261. txtwht='\e[0;37m' # White
  262. bldblk='\e[1;30m' # Black - Bold
  263. bldred='\e[1;31m' # Red
  264. bldgrn='\e[1;32m' # Green
  265. bldylw='\e[1;33m' # Yellow
  266. bldblu='\e[1;34m' # Blue
  267. bldpur='\e[1;35m' # Purple
  268. bldcyn='\e[1;36m' # Cyan
  269. bldwht='\e[1;37m' # White
  270. unkblk='\e[4;30m' # Black - Underline
  271. undred='\e[4;31m' # Red
  272. undgrn='\e[4;32m' # Green
  273. undylw='\e[4;33m' # Yellow
  274. undblu='\e[4;34m' # Blue
  275. undpur='\e[4;35m' # Purple
  276. undcyn='\e[4;36m' # Cyan
  277. undwht='\e[4;37m' # White
  278. bakblk='\e[40m'   # Black - Background
  279. bakred='\e[41m'   # Red
  280. badgrn='\e[42m'   # Green
  281. bakylw='\e[43m'   # Yellow
  282. bakblu='\e[44m'   # Blue
  283. bakpur='\e[45m'   # Purple
  284. bakcyn='\e[46m'   # Cyan
  285. bakwht='\e[47m'   # White
  286. txtrst='\e[0m'    # Text Reset
  287.  
  288.  
  289.  
  290. ##################################################
  291. # This bashrc's current prompt           #
  292. ##################################################
  293.  
  294. PS1='\[\033]0;\w\007\]\[\e[35;1m\]\u\[\e[0m\]\[\e[32m\]@\h\[\e[34m\]\w \[\e[33m\]\$ \[\e[0m\]'  # purple, green, blue prompt w/default black & dir title
  295.  
  296.  
  297.  
  298. ##################################################
  299. # More command prompt choices (CHOOSE ONE, either#
  300. # one of single lines below, or one of the   #
  301. # fancier ones farther below - just uncomment    #
  302. # one want and comment mine above)       #
  303. ##################################################
  304.  
  305. # PS1='\[\033[01;31m\]\u\[\033[01;36m\]@\[\033[01;32m\]\h\[\033[01;33m\]:\[\033[01;33m\]\w\n\[\033[01;31m\]\$ \[\033[00;32m\]'  # red, cyan, green, yellow with green output
  306. # PS1="\[\033[01;32m\]\u@\h\[\033[01;34m\] \w \$\[\033[00m\] "                  # green and blue prompt with pc name & default black output
  307. # PS1="\[\033[0;31m\][\u] [ \w ] \[\033[0m\] \n # "                     # red with default black output (2-tier)
  308. # PS1="\[\033[0;33m\][\!]\`if [[ \$? = "0" ]]; then echo "\\[\\033[32m\\]"; else echo "\\[\\033[31m\\]"; fi\`[\u.\h: \`if [[ `pwd|wc -c|tr -d " "` > 18 ]]; then echo "\\W"; else echo "\\w"; fi\`]\$\[\033[0m\] "; echo -ne "\033]0;`hostname -s`:`pwd`\007"   # yellow and green with default black output
  309. # PS1="\[\033[0;33m\][\!]\`if [[ \$? = "0" ]]; then echo "\\[\\033[32m\\]"; else echo "\\[\\033[31m\\]"; fi\`[\u.\h: \`if [[ `pwd|wc -c|tr -d " "` > 18 ]]; then echo "\\W"; else echo "\\w"; fi\`]\$\[\033[0m\] "; echo -ne "\033]0;`hostname -s`:`pwd`\007"   # yellow, green, w/black output w/color change upon bad command
  310. # PS1="\[\033[0;34m\][\u] \[\033[0;0m\]\w \[\033[0m\]$ "                    # blue username and default black output
  311. # PS1="\[\033[0;34m\][\u] \[\033[0;31m\][ \w ] \[\033[0m\] \n >> "              # blue and red with default black output (2-tier)
  312. # PS1="\[\033[0;34m\][\u] \[\033[0;33m\][ \t ] \[\033[0;31m\][ \w ] \[\033[0m\] \n >> "     # blue, yellow, red with default black output (2-tier)
  313. # PS1='\[\033[1;30m\][\[\033[0;37m\]${PIPESTATUS}\[\033[1;30m\]:\[\033[0;37m\]${SHLVL}\[\033[1;30m\]:\[\033[0;37m\]\j\[\033[1;30m\]][\[\033[1;34m\]\u\[\033[0;34m\]@\[\033[1;34m\]\h\[\033[1;30m\]:\[\033[0;37m\]`tty | sed s/\\\\\/dev\\\\\/\//g`\[\033[1;30m\]]\[\033[0;37m\][\[\033[1;37m\]\W\[\033[0;37m\]]\[\033[1;30m\] \$\[\033[00m\] '                                  # grey and blue with default black output
  314. # PS1="[\[\033[1;34m\]\u\[\033[0m\]@\h \W]\\$ "                         # blue username with default colors (black)
  315. # PS1="[\!] \033[1;36m[ \u@\h ]\033[1;32m\] [ \t ] [ \d ]\n\033[1;33m\[[ \w ] \033[00m\\n\[\e[30;1m\](\[\e[32;1m\]\$(/bin/ls -1 | /usr/bin/wc -l | /bin/sed 's: ::g') files, \$(/bin/ls -lah | /bin/grep -m 1 total | /bin/sed 's/total //')b\[\e[30;1m\]) \[\e[0m\] $: "   # black, cyan, green, yellow, default black output (2-tier)
  316. # PS1="[\[\033[32m\]\w]\[\033[0m\]\n\[\033[1;36m\]\u\[\033[1;33m\]-> \[\033[0m\]"       # black, green, cyan, yellow, w/black output w/full path (2-tier)
  317. # PS1="\[\033[34m\]   \u@\h `tty | sed 's/\/dev\///'` \t \d \[\033[35m\]\w/ \n\[\033[34m\] $\[\033[0m\] "   # cyan with green output
  318. # PS1="\[\033[35m\]\t\[\033[m\]-\[\033[36m\]\u\[\033[m\]@\[\033[32m\]\h:\[\033[33;1m\]\w\[\033[m\]\$ "  # purple, cyan, black, green, yellow, default black
  319. # PS1="\[\033[35m\]\t\[\033[m\]-\[\033[36m\]\u\[\033[m\]@\[\033[32m\]\h:\[\033[33;1m\]\w\[\033[m\]\$ "  # purple, cyan, black, green, yellow, w/black output
  320. # PS1="\[\033[36m\]   \u@\h `tty | sed 's/\/dev\///'` \t \d \[\033[32m\]\w/ \n\[\033[36m\] $\[\033[0m\] "   # blue with purple output
  321. # PS1=">\[\033[s\]\[\033[1;\$((COLUMNS-4))f\]\$(date +%H:%M)\[\033[u\]"             # trimmed up prompt with clock using default colors (black)
  322. # PS1='C:${PWD//\//\\\}>'                                   # change prompt to MS-DOS one (joke)
  323. # PS1='${debian_chroot:+($debian_chroot)}\[[ \033[01;31m\]\w\[\033[00m\]] '         # basic red with default black output
  324. # PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[0;31m\]\$ \[\e[m\]\[\e[0;32m\]'   # red and blue prompt with green output
  325. # PS1='\[\e[0;32m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[1;32m\]\$\[\e[m\] \[\e[1;37m\]'   # green and blue prompt with light grey output
  326. # PS1='\[\e[0;32m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[1;32m\]\$\[\e[m\]'            # green and blue prompt with default black output
  327. # PS1='\e[1;31;47m\u \e[1;32;47mon \h \e[1;35;47m\d \@\e[0;0m\n\e[1;31m[dir.= \w] \# > \e[0;0m' # red, green, purple, red with default black output
  328. # PS1='\[\e[1;31m\][\[\e[0;37m\]\u\[\e[1;31m\]@\[\e[0;37m\]\h \W\[\e[1;31m\]]\$\[\e[0m\] '  # red and grey with default black output
  329. # PS1='\[\e[1;31m\][\u@\h \W]\$\[\e[0m\] '                          # red color with default black output
  330. # PS1='\[\e[1;32m\]\u@\H:\[\e[m\] \[\e[1;37m\]\w\[\e[m\]\n\[\e[1;33m\]hist:\! \[\e[0;33m\] \[\e[1;31m\]jobs:\j \$\[\e[m\] ' # green, yellow, red, grey and default black output (2-tier)
  331. # PS1='\[\e[1;32m\]\u@\H:\[\e[m\] \[\e[1;37m\]\w\[\e[m\]\n\[\e[1;33m\]hist:\! \[\e[0;33m\] \[\e[1;31m\]jobs:\j \$\[\e[m\] ' # green, yellow, red, w/black output (2-tier) w/background job count
  332. # PS1='\[\e[1;32m\][\u@\h \W]\$\[\e[0m\] '                          # green color with default black output
  333. # PS1='\e[1;33;47m\u \e[1;32;47mon \h \e[1;35;47m\d \@\e[0;0m\n\e[1;34m[dir.= \w] \# > \e[0;0m' # yellow, green, purple, cyan with default black output
  334. # PS1="\[\e[1;33m\] > \[\033[0m\]"                              # basic yellow with default black output & nothing else
  335. # PS1='\[\e[1m\]\h:\w\$\[\e[0m\] '                              # black-bold with default colors (black)
  336. # PS1="\[\e]2;\u@\H \w\a\e[30;1m\]>\[\e[0m\] "                          # trimmed up prompt w/black arrow & title is current dir.
  337. # PS1="\[\e[30;1m\]\w> \[\e[0m\]"                               # trimmed up prompt with just black arrow and default colors
  338. # PS1="\[\e[36;1m\]\u@\[\e[32;1m\]\H> \[\e[0m\]"                        # cyan and green prompt with default black output
  339. # PS1="\[\e[37;1m\]-{\[\e[34;1m\]\u@\h\[\e[37;1m\]}-\n\[\e[37;1m\](\[\e[34;1m\]\w: \$(/bin/ls -1 | /usr/bin/wc -l | /bin/sed 's: ::g') files, \$(/bin/ls -lah | /bin/grep -m 1 total | /bin/sed 's/total //')b\[\e[37;1m\])\n--> \[\e[0m\]"     # grey and cyan w/black output (2-tier) w/dir size
  340. # PS1='\[\e[41m\]\[\e[1;37m\] \u \[\e[47m\]\[\e[1;30m\] \W \[\e[0m\]\[\e[1;37m\]\[\e[42m\] # \[\033[0m\] '  # red, grey, green boxed with default black
  341. # PS1='\[\e[45m\]\[\e[1;37m\] \u@\h \[\e[47m\]\[\e[1;30m\] \W \[\e[0m\]\[\e[1;37m\]\[\e[42m\] > \[\033[0m\] '   # purple, grey, green boxed with default black
  342. # PS1='\[\e[m\n\e[0;33m\][$$:$PPID \j:\!\[\e[0;33m\]]\[\e[0;36m\] \T \d \[\e[1;34m\][\[\e[1;34m\]\u@\H\[\e[1;31m\]:\[\e[0;37m\]${SSH_TTY} \[\e[0;32m\]+${SHLVL}\[\e[1;30m\]] \[\e[1;31m\]\w\[\e[0;30m\] \n($SHLVL:\!)\$ '               # yellow, cyan, red, blue, white, green, black, red w/ default black output
  343. # PS1="\`if [ \$? = 0 ]; then echo \[\e[33m\]^_^\[\e[0m\]; else echo \[\e[31m\]O_O\[\e[0m\]; fi\`[\u@\h:\w]\\$ "    # all black with happy face (yellow/red) upon successful completion
  344. # PS1="\`if [ \$? = 0 ]; then echo \[\e[33m\]^_^\[\e[0m\]; else echo \[\e[31m\]O_O\[\e[0m\]; fi\`[\u@\h:\w]\\$ "    # basic prompt but with yellow smiley
  345. # PS1="\n\[\033[32;1m\]It's \t\[\033[33;1m\] Currently browsing \[\033[1;36m\]\w \[\033[33;1m\]directory\n\[\033[34;1m\]\`if [ \$? = 0 ]; then echo \[\e[37m\]Last Command Was Successfully Executed \[\e[32m\]^_^\[\e[0m\]; else echo \[\e[37m\]Smeggin Hell !!! Last Command Was Unknown \[\e[32m\]O_O\[\e[0m\]; fi\` \n\[\033[31m\]What is thy bidding, my master? \n\n\[\033[34;1m\]"               # green, yellow, grey, green, red, w/cyan output (3-tier) Star Wars version
  346. # PS1="\n\[\033[35m\]\$(/bin/date)\n\[\033[32m\]\w\n\[\033[1;31m\]\u@\h: \[\033[1;34m\]\$(/usr/bin/tty | /bin/sed -e 's:/dev/::'): \[\033[1;36m\]\$(/bin/ls -1 | /usr/bin/wc -l | /bin/sed 's: ::g') files \[\033[1;33m\]\$(/bin/ls -lah | /bin/grep -m 1 total | /bin/sed 's/total //')b\[\033[0m\] -> \[\033[0m\]"    - purple, green, blue, cyan, yellow, with default black output (3-tier)
  347. # PS1="\n\[\033[35m\]\$(/bin/date)\n\[\033[32m\]\w\n\[\033[1;31m\]\u@\h: \[\033[1;34m\]\$(/usr/bin/tty | /bin/sed -e 's:/dev/::'): \[\033[1;36m\]\$(/bin/ls -1 | /usr/bin/wc -l | /bin/sed 's: ::g') files \[\033[1;33m\]\$(/bin/ls -lah | /bin/grep -m 1 total | /bin/sed 's/total //')b\[\033[0m\] -> \[\033[0m\]"                                                # purple, red, blue, cyan, yellow, w/white output (3-tier)
  348. # PS1="\n\[$bldgrn\][\[$txtrst\]\w\[$bldgrn\]]\[$bldwht\]\n\[$bldwht\][\[$txtrst\]\t\[$bldwht\]]\[$bldylw\]$ \[$txtrst\]"   # green, black, grey, yellow with default black output (3-tier)
  349. # PS1="\n#--[\[\e[1;36m\]\u@\h\[\e[m\]]-[\[\e[1;34m\]\w\[\e[m\]]-[\$(date +%k:%M)]-->\n"    # black, cyan, blue, black, w/black output (2-tier)
  350. # PS1="\n\[\e[30;1m\]\[\016\]l\[\017\](\[\e[34;1m\]\u@\h\[\e[30;1m\])-(\[\e[34;1m\]\j\[\e[30;1m\])-(\[\e[34;1m\]\@ \d\[\e[30;1m\])->\[\e[30;1m\]\n\[\016\]m\[\017\]-(\[\[\e[32;1m\]\w\[\e[30;1m\])-(\[\e[32;1m\]\$(/bin/ls -1 | /usr/bin/wc -l | /bin/sed 's: ::g') files, \$(/bin/ls -lah | /bin/grep -m 1 total | /bin/sed 's/total //')b\[\e[30;1m\])--> \[\e[0m\]"              # grey, cyan, green, w/black output (2-tier) w/ dir. info
  351. # PS1="\n\[\e[30;1m\]?(\[\e[34;1m\]\u@\h\[\e[30;1m\])-(\[\e[34;1m\]\j\[\e[30;1m\])-(\[\e[34;1m\]\@ \d\[\e[30;1m\])->\[\e[30;1m\]\n??(\[\e[32;1m\]\w\[\e[30;1m\])-(\[\e[32;1m\]$(/bin/ls -1 | /usr/bin/wc -l | /bin/sed 's: ::g') files, $(/bin/ls -lah | /bin/grep -m 1 total | /bin/sed 's/total //')b\[\e[30;1m\])--> \[\e[0m\]"  # black, cyan, green w/black output (2-tier)
  352. # PS1="\n\[\e[32;1m\](\[\e[37;1m\]\u\[\e[32;1m\])-(\[\e[37;1m\]jobs:\j\[\e[32;1m\])-(\[\e[37;1m\]\w\[\e[32;1m\])\n(\[\[\e[37;1m\]! \!\[\e[32;1m\])-> \[\e[0m\]" # grey and green with default black output (3-tier)
  353. # PS1="\n\[\e[m\][\[\033[01;32m\]\w\[\e[m\]] [\t] \n\[\033[01;33m\]$ \[\033[00m\]"      # green, black, yellow, with default black output (3-tier)
  354. # PS1="\t \u@\h\$ "                                     # simple prompt with time (black)
  355. # PS1="\t \u@\h `tty | sed 's/\/dev\///'` \w \$ "                       # longer prompt with time (black)
  356. # PS1="\u@\h\$ "                                        # simple default prompt (black)
  357. # PS1="\u@\h `tty | sed 's/\/dev\///'` \w \$ "                          # longer prompt with brief info (black)
  358. # PS1='[\u@\h \W]\$ '                                       # default colors (black)
  359. # PS1="\u@\h [\w] \$ "                                      # simple prompt with directory (black)
  360. # PS1="\u `tty | sed 's/\/dev\///'` [\W] \$ "                           # prompt with brief info (black)
  361.  
  362.  
  363.  
  364. ##################################################
  365. # Jsnx's prompt of power (disabled by a single   #
  366. # "#")                       #
  367. ##################################################
  368.  
  369. ## I used to have the prompt set up as a bunch of functions; but that
  370. ## didn't work very well with sh. Now, I have mastered the various
  371. ## levels of evaluation and quoting of the shell and can confidently
  372. ## write hideous macros!
  373. # DARK="\[\e[01;34m\]"
  374. # NORM="\[\e[01;32m\]"
  375. # FADE="\[\e[01;30m\]"
  376. # REST="\[\e[00;00m\]"
  377. # HIGH="\[\e[01;33m\]"
  378. # dir="pwd -P | awk '{ printf \"%-65.65s\", \$1 }'"
  379. # sub="sed -r 's/^/$NORM/ ; s|/|$FADE&$NORM|g ; s/:/$DARK&$NORM/g'"
  380. # t="date +%H:%M"
  381. # hist="history 1 | xargs echo '' | awk '{ printf \"%03.3d\", \$1 + 1 }'"
  382. # warn="[ $USER = root ] && echo -n '$HIGH' || echo -n '$FADE'"
  383. # bang="echo -ne '\x21'"  ## this gives me a single '!' in bash and sh
  384. # prompt=" $DARK: \`$dir | $sub\` \`$warn;$bang;\`$NORM\`$hist\` \`$t | $sub\`
  385. # $DARK:\`$warn\`; $REST"
  386. # prepend=''
  387. # if [ "${TERM}" = "xterm" ]
  388. # then
  389. #  my_tty=`tty | awk -F/ '{ print $3 $4}'`
  390. #  xterm_title="\[\e]0;${my_tty} \u@\H\007\]"
  391. #  prepend="${xterm_title}"
  392. # fi
  393. ## export  PROMPT_COMMAND="export PS1=\"${prepend}${prompt}\""
  394. # export  PS1="${prepend}${prompt}"
  395. # export  PS2='  '
  396.  
  397.  
  398.  
  399. ##################################################
  400. # Nate Mitchell's (Kasyx's) Bash Prompt (red with#
  401. # green dashes and black output) (disabled by a  #
  402. # single "#")                    #
  403. ##################################################
  404.  
  405. # function prompt() {
  406. # Black="\e[30m"
  407. # Red="\e[31m"
  408. # Green="\e[32m"
  409. # LightGreen="\e[32;1m"
  410. # Blue="\e[34m"
  411. # LightBlue="\e[34;1m"
  412. # NC="\e[0m" # No Color
  413. # PS1="\[$LightGreen\033(0\154\033(B\][\[\033(0\161\161\033(B$Green\][\[$Red\]\u@\h\[$Green\]]\[\033(0\161\033(B\][\[$Red\]\w\[$Green\]]\[\033(0\161\033(B\][\[$Red\]\!\[$Green\]]\[\033(0\161\161\033(B\]]\n\[$LightGreen\033(0\155\161\033(B$Green\][\[$Red\]\#\[$Green\]]\[\033(0\161\033(B\][\[$Red\]\$\[$Green\]]\[\033(0\161\161\033(B\][\[$NC\]"
  414. # PS2="> "
  415. # }
  416. # prompt
  417.  
  418.  
  419.  
  420. ##################################################
  421. # Wolfman's prompt (disabled by a single "#")    #
  422. ##################################################
  423.  
  424. ## Fancy PWD display function
  425. ## The home directory (HOME) is replaced with a ~
  426. ## The last pwdmaxlen characters of the PWD are displayed
  427. ## Leading partial directory names are striped off
  428. ## /home/me/stuff          -> ~/stuff               if USER=me
  429. ## /usr/share/big_dir_name -> ../share/big_dir_name if pwdmaxlen=20
  430. # function bash_prompt_command() {
  431. #    # How many characters of the $PWD should be kept
  432. #    local pwdmaxlen=25
  433. #    # Indicate that there has been dir truncation
  434. #    local trunc_symbol=".."
  435. #    local dir=${PWD##*/}
  436. #    pwdmaxlen=$(( ( pwdmaxlen < ${#dir} ) ? ${#dir} : pwdmaxlen ))
  437. #    NEW_PWD=${PWD/#$HOME/\~}
  438. #    local pwdoffset=$(( ${#NEW_PWD} - pwdmaxlen ))
  439. #    if [ ${pwdoffset} -gt "0" ]
  440. #    then
  441. #        NEW_PWD=${NEW_PWD:$pwdoffset:$pwdmaxlen}
  442. #        NEW_PWD=${trunc_symbol}/${NEW_PWD#*/}
  443. #    fi
  444. # }
  445. # function bash_prompt() {
  446. #    case $TERM in
  447. #     xterm*|rxvt*)
  448. #         local TITLEBAR='\[\033]0;\u:${NEW_PWD}\007\]'
  449. #          ;;
  450. #     *)
  451. #         local TITLEBAR=""
  452. #          ;;
  453. #    esac
  454. #    local NONE="\[\033[0m\]"    # unsets color to term's fg color
  455. #    # regular colors
  456. #    local K="\[\033[0;30m\]"    # black
  457. #    local R="\[\033[0;31m\]"    # red
  458. #    local G="\[\033[0;32m\]"    # green
  459. #    local Y="\[\033[0;33m\]"    # yellow
  460. #    local B="\[\033[0;34m\]"    # blue
  461. #    local M="\[\033[0;35m\]"    # magenta
  462. #    local C="\[\033[0;36m\]"    # cyan
  463. #    local W="\[\033[0;37m\]"    # white
  464. #    # emphasized (bolded) colors
  465. #    local EMK="\[\033[1;30m\]"
  466. #    local EMR="\[\033[1;31m\]"
  467. #    local EMG="\[\033[1;32m\]"
  468. #    local EMY="\[\033[1;33m\]"
  469. #    local EMB="\[\033[1;34m\]"
  470. #    local EMM="\[\033[1;35m\]"
  471. #    local EMC="\[\033[1;36m\]"
  472. #    local EMW="\[\033[1;37m\]"
  473. #    # background colors
  474. #    local BGK="\[\033[40m\]"
  475. #    local BGR="\[\033[41m\]"
  476. #    local BGG="\[\033[42m\]"
  477. #    local BGY="\[\033[43m\]"
  478. #    local BGB="\[\033[44m\]"
  479. #    local BGM="\[\033[45m\]"
  480. #    local BGC="\[\033[46m\]"
  481. #    local BGW="\[\033[47m\]"
  482. #    local UC=$W                 # user's color
  483. #    [ $UID -eq "0" ] && UC=$R   # root's color
  484. ##    PS1="$TITLEBAR ${EMK}[${UC}\u${EMK}@${UC}\h ${EMB}\${NEW_PWD}${EMK}]${UC}\\$ ${NONE}"
  485. #    # without colors: PS1="[\u@\h \${NEW_PWD}]\\$ "
  486. #    # extra backslash in front of \$ to make bash colorize the prompt
  487. # }
  488. # PROMPT_COMMAND=bash_prompt_command
  489. # bash_prompt
  490. # unset bash_prompt
  491.  
  492.  
  493.  
  494. ##################################################
  495. # Emmanuel Rouat's shell prompt (fancy all   #
  496. # black with info)               #
  497. ##################################################
  498.  
  499. # if [[ "${DISPLAY%%:0*}" != "" ]]; then
  500. #    HILIT=${red}   # remote machine: prompt will be partly red
  501. # else
  502. #    HILIT=${cyan}  # local machine: prompt will be partly cyan
  503. # fi
  504. ##   --> Replace instances of \W with \w in prompt functions below
  505. ## + --> to get display of full path name.
  506. # function fastprompt()
  507. # {
  508. #    unset PROMPT_COMMAND
  509. #    case $TERM in
  510. #        *term | rxvt )
  511. #            PS1="${HILIT}[\h]$NC \W > \[\033]0;\${TERM} [\u@\h] \w\007\]" ;;
  512. #        linux )
  513. #            PS1="${HILIT}[\h]$NC \W > " ;;
  514. #        *)
  515. #            PS1="[\h] \W > " ;;
  516. #    esac
  517. # }
  518. # function _powerprompt()
  519. # {
  520. #    LOAD=$(uptime|sed -e "s/.*: \([^,]*\).*/\1/" -e "s/ //g")
  521. # }
  522. #
  523. # function powerprompt()
  524. # {
  525. #    PROMPT_COMMAND=_powerprompt
  526. #    case $TERM in
  527. #        *term | rxvt  )
  528. #            PS1="${HILIT}[\A - \$LOAD]$NC\n[\u@\h \#] \W > \
  529. #                 \[\033]0;\${TERM} [\u@\h] \w\007\]" ;;
  530. #        linux )
  531. #            PS1="${HILIT}[\A - \$LOAD]$NC\n[\u@\h \#] \W > " ;;
  532. #        * )
  533. #            PS1="[\A - \$LOAD]\n[\u@\h \#] \W > " ;;
  534. #    esac
  535. # }
  536. # powerprompt     # This is the default prompt -- might be slow.
  537. #                # If too slow, use fastprompt instead. ...
  538.  
  539.  
  540.  
  541. ##################################################
  542. # Xterm windowdressing (cyan and black with  #
  543. # grey output info prompt( (disabled by a    #
  544. # single '#')                    #
  545. ##################################################
  546.  
  547. # function elite()
  548. #  {
  549. #  local GRAY="\[\033[1;30m\]"
  550. #  local LIGHT_GRAY="\[\033[0;37m\]"
  551. #  local CYAN="\[\033[0;36m\]"
  552. #  local LIGHT_CYAN="\[\033[1;36m\]"
  553. #  case $TERM in
  554. #      xterm*)
  555. #          local TITLEBAR='\[\033]0;\u@\h:\w\007\]'
  556. #          ;;
  557. #      *)
  558. #          local TITLEBAR=""
  559. #          ;;
  560. #  esac
  561. #  local GRAD1=$(tty|cut -d/ -f3)
  562. #  PS1="$TITLEBAR\
  563. #  $GRAY-$CYAN-$LIGHT_CYAN(\
  564. #  $CYAN\u$GRAY@$CYAN\h\
  565. #  $LIGHT_CYAN)$CYAN-$LIGHT_CYAN(\
  566. #  $CYAN\#$GRAY/$CYAN$GRAD1\
  567. #  $LIGHT_CYAN)$CYAN-$LIGHT_CYAN(\
  568. #  $CYAN\$(date +%H%M)$GRAY/$CYAN\$(date +%d-%b-%y)\
  569. #  $LIGHT_CYAN)$CYAN-$GRAY-\
  570. #  $LIGHT_GRAY\n\
  571. #  $GRAY-$CYAN-$LIGHT_CYAN(\
  572. #  $CYAN\$$GRAY:$CYAN\w\
  573. #  $LIGHT_CYAN)$CYAN-$GRAY-$LIGHT_GRAY "
  574. #  PS2="$LIGHT_CYAN-$CYAN-$GRAY-$LIGHT_GRAY "
  575. #  }
  576. # PROMPT_COMMAND=elite
  577.  
  578.  
  579.  
  580. ##################################################
  581. # Another prompt =               #
  582. # (PS1="\[\e]2;\u@\H \w\a\e[30;1m\]>\[\e[0m\]    #
  583. # " but fixed for various systems - simple   #
  584. # prompt that shows currently directory in   #
  585. # title)                     #
  586. ##################################################
  587.  
  588. # if [ "$TERM" = "linux" ]
  589. # then
  590. #   # we're on the system console or maybe telnetting in
  591. #   export PS1="\[\e[32;1m\]\u@\H > \[\e[0m\]"
  592. # else
  593. #   # we're not on the console, assume an xterm
  594. #   export PS1="\[\e]2;\u@\H \w\a\e[32;1m\]>\[\e[0m\] "
  595. # fi
  596.  
  597.  
  598.  
  599. ##################################################
  600. # Yet another prompt (simple black prompt with   #
  601. # the word 'bash$' only)             #
  602. ##################################################
  603.  
  604. ## Check if running in an xterm and give a more suitable prompt
  605. ## (two alternative blocks given below)
  606. ## mesg y allows talk(1) requests, here only if not an xterm
  607. ## Gives informative prompt, puts user,host,path in xterm title
  608. ## Comment or uncomment all of the following lines ('case' to 'esac')
  609. # case $TERM in
  610. #     xterm*)
  611. #        PS1="\[\033]0;\u@\h: \w\007\]bash\$ "
  612. #       ;;
  613. #  *)
  614. #      PS1="\t \u@\h `tty | sed 's/\/dev\///'`\$ "
  615. #       mesg y
  616. #        ;;
  617. # esac
  618.  
  619.  
  620.  
  621. ##################################################
  622. # Still another prompt (cyan and red with    #
  623. # green output info prompt) (disabled by a   #
  624. # single '#')                    #
  625. ##################################################
  626.  
  627. ### Colourful prompts
  628. ### Comment or uncomment all of the following lines ('case' to 'esac')
  629. ## case $TERM in
  630. ##      xterm*)
  631. ##          TERM=xterm-color; export TERM
  632. ##          PS1="\[\033[36m\]   \u@my_computer `tty | sed 's/\/dev\///'` \t \d \[\033[35m\]\w/ \n\[\033[36m\] $\[\033[0m\] "
  633. ##          ;;
  634. ##      *)
  635. #          PS1="`setterm -bold on` \[\033[36m\] \u@my_computer `tty | sed 's/\/dev\///'` \t \d \[\033[1;31m\]\w/ \n\[\033[36m\]! \[\033[1;32m\] `setterm -#bold off`"
  636. #    # this adds a bg color; comment out the above
  637. ##      PS1="\[\033[35m\]   \u@my_computer `tty | sed 's/\/dev\///'` \t \d \[\033[32m\]\w/ \n\[\033[36m\] $\[\033[44;1;36m\] `setterm -bold on` "
  638. ##          mesg y
  639. ##          ;;
  640. ## esac
  641.  
  642.  
  643.  
  644. ##################################################
  645. # More PROMPT_COMMANDS               #
  646. ##################################################
  647.  
  648. ###### Annoying PROMPT_COMMAND animation
  649. # PROMPT_COMMAND='seq $COLUMNS | xargs -IX printf "%Xs\r" @'
  650.  
  651.  
  652.  
  653. ###### Share history between using multiple commands (press enter before get history from other bash shells)
  654. # PROMPT_COMMAND='history -a && history -n'
  655.  
  656.  
  657.  
  658. ###### Shows date
  659. # PROMPT_COMMAND='date +%k:%m:%S'
  660.  
  661.  
  662.  
  663. ###### Shows memory, load average, and history
  664. # PROMPT_COMMAND='history -a;echo -en "\033[m\033[38;5;2m"$(( `sed -nu "s/MemFree:[\t ]\+\([0-9]\+\) kB/\1/p" /proc/meminfo`/1024))"\033[38;5;22m/"$((`sed -nu "s/MemTotal:[\t ]\+\([0-9]\+\) kB/\1/Ip" /proc/meminfo`/1024 ))MB"\t\033[m\033[38;5;55m$(< /proc/loadavg)\033[m"'
  665.  
  666.  
  667.  
  668. ###### Shows the return value of the last executed command (using smileys as to whether it was successful or not)
  669. # PROMPT_COMMAND='RET=$?; if [[ $RET -eq 0 ]]; then echo -ne "\033[0;32m$RET\033[0m ;)"; else echo -ne "\033[0;31m$RET\033[0m ;("; fi; echo -n " "'
  670.  
  671.  
  672.  
  673. ##################################################
  674. ##################################################
  675. ##################################################
  676.  
  677.  
  678.  
  679.  
  680.  
  681.  
  682.  
  683.  
  684. ######################################################################################################################################################
  685. ###### BASH SETTINGS ###### BASH SETTINGS ###### BASH SETTINGS ###### BASH SETTINGS ###### BASH SETTINGS ###### BASH SETTINGS ###### BASH SETTINGS ######
  686. ######################################################################################################################################################
  687.  
  688.  
  689.  
  690.  
  691.  
  692.  
  693.  
  694.  
  695. # autoload -U compinit
  696. # compinit
  697. export BLOCKSIZE=K
  698. export BROWSER='firefox'
  699. # export BROWSER=$(find_alternatives chromium-browser google-chrome opera firefox firefox-bin iceweasel konqueror w3m lynx) # uses function 'find_alternatives'
  700. # export CDPATH=.:~:~/src:/etc
  701. # export DISPLAY=:79
  702. # export EDITOR="gedit -w --resume" Typing 'fc' # open last command for editing in gedit, then execute on save
  703. export EDITOR='vi'
  704. # export ftp_proxy=${MY_PROXY}
  705. # export GPG_TTY='tty'              # gpg-agent says it needs this
  706. # export GREP_OPTIONS='-D skip --binary-files=without-match --ignore-case'      # most commonly used grep options
  707. export HISTCONTROL=ignoreboth:erasedups     # for 'ignoreboth': ignore duplicates and /^\s/
  708. # export HISTCONTROL=ignoredups         # don't put duplicate lines in the history. See bash(1) for more options
  709. # export HISTFILE='$HOME/.history'
  710. # export HISTFILESIZE=10000
  711. # export HISTFILESIZE=${HISTSIZE}       # bash will remember N commands
  712. export HISTIGNORE='&:bg:fg:ll:h'
  713. # export HISTIGNORE='${HISTIGNORE:+$HISTIGNORE:}la:ll:lah:lat:;a:-:fg:bg:j:sync:esu:rma:rmp:fol:pfol'
  714. # export HISTIGNORE="&:ls:[bf]g:exit"       # duplicate entries in bash history, as well as ls, bg, fg & exit, making for cleaner bash history
  715. # export HISTIGNORE="&:ls:ll:la:l.:pwd:exit:clear"
  716. # export HISTIGNORE='pwd:cd:ls:ls -l:'      # ignore commands given
  717. export HISTSIZE=10000
  718. # export HISTTIMEFORMAT='| %d/%m/%y %T | '  # make 'History' Show The Date For Each Command
  719. # export HISTTIMEFORMAT='%F %T '        # adds date and time to history
  720. export HISTTIMEFORMAT='%H:%M > '
  721. # export HISTTIMEFORMAT='%s'            # the beloved Second of Our Linux
  722. # export HISTTIMEFORMAT='%Y-%b-%d::%Hh:%Mm:%Ss '
  723. export HISTTIMEFORMAT='%Y-%m-%d_%H:%M:%S_%a  '  # makes history display in YYYY-MM-DD_HH:MM:SS_3CharWeekdaySpaceSpace format
  724. export HOSTFILE=$HOME/.hosts            # put list of remote hosts in ~/.hosts ...
  725. # export http_proxy=${MY_PROXY}
  726. # export https_proxy=${MY_PROXY}
  727. # export IGNOREEOF=1                # prevent CTRL-D from immediately logging out
  728. # export INPUTRC=/etc/inputrc           # it's possible that this will make bash find my delete key (and everything else)((but i don't think it did))
  729. # export LC_COLLATE="en_CA.utf8"        # change sorting methods [a-Z] instead of [A-Z]
  730. export LESSCHARSET='latin1'
  731. export LESS='-i -N -w  -z-4 -g -e -M -X -F -R -P%t?f%f \'
  732. # export LESSOPEN="|lesspipe.sh %s"; export LESSOPEN
  733. export LESSOPEN='|/usr/bin/lesspipe.sh %s 2>&-' # use this if lesspipe.sh exists
  734. # export LESS="-QR"             # tell less not to beep and also display colours
  735. # export LESS='-R'
  736. # export LESS_TERMCAP_mb=$'\E[01;31m'       # less colors for Man pages # begin blinking
  737. # export LESS_TERMCAP_md=$'\E[01;38;5;74m'      # less colors for Man pages # begin bold
  738. # export LESS_TERMCAP_me=$'\E[0m'               # less colors for Man pages # end mode
  739. # export LESS_TERMCAP_se=$'\E[0m'               # less colors for Man pages # end standout-mode
  740. # export LESS_TERMCAP_so=$'\E[38;5;246m'        # less colors for Man pages # begin standout-mode - info box
  741. # export LESS_TERMCAP_ue=$'\E[0m'               # less colors for Man pages # end underline
  742. # export LESS_TERMCAP_us=$'\E[04;38;5;146m'     # less colors for Man pages # begin underline
  743. # export MY_PROXY='http://YOUR_USERNAME:YOUR_PASSWORD@PROXY_IP:PROXY_PORT/'
  744. # export OOO_FORCE_DESKTOP=gnome        # openoffice preferences
  745. export PAGER='less -e'
  746. # export PATH=$PATH:$HOME/scripts
  747. # export PILOTRATE=57600            # make pilot-xfer go faster than 9600
  748. export TERM='xterm'
  749. export TIMEFORMAT=$'\nreal %3R\tuser %3U\tsys %3S\tpcpu %P\n'
  750. export TMOUT=600                # auto logout after n seconds of inactivity
  751. # export USER_CLIENT=deluge
  752. # export USER_DPRT=22218
  753. # export USER_OPRT=47426
  754. # export USER_VPRT=79
  755. # export USER_WPRT=30818
  756. export VISUAL='vi'
  757. # export wpsetters=feh
  758. # ${file%\.[^.]*}               # to remove filename extensions in bash
  759. # fortune -a                    # fortunes at each new shell
  760. # mesg n                            #
  761. set -b                      # causes output from background processes to be output right away, not on wait for next primary prompt
  762. # set bell-style visible            # I hate noise
  763. # set completion-ignore-case on         # complete things that have been typed in the wrong case
  764. # set -o ignoreeof              # can't c-d out of shell
  765. # set -o noclobber              # disallow > to work on files that already exist (prevents catting over file)
  766. set -o notify                   # notify when jobs running in background terminate
  767. # set -o nounset                # attempt to use undefined variable outputs error message and forces exit (messes up completion if enabled)
  768. # set +o nounset                    # otherwise some completions will fail
  769. # setopt autopushd pushdminus pushdsilent pushdtohome
  770. # setopt correct
  771. # setopt extendedglob
  772. # setopt hist_ignore_space              # prepend ' ' to not be saved
  773. # setopt hist_verify                    # verify when using !
  774. # setopt nocheckjobs                    # don't complain about background jobs on e
  775. # setopt no_clobber                     # don't overwrite files when redirect
  776. # setopt nohup                          # don't kill bg jobs when tty quits
  777. # setopt printexitvalue                 # print exit value from jobs
  778. # setopt share_history
  779. # set -o xtrace                 # useful for debuging
  780. # setterm -blength 0                # set the bell duration in milliseconds (silence the beeps)
  781. # set visible-stats on              # when listing possible file completions, put / after directory names and * after programs
  782. shopt -s cdable_vars                # set the bash option so that no '$' is required (disallow write access to terminal)
  783. shopt -s cdspell                # this will correct minor spelling errors in a cd command
  784. shopt -s checkhash
  785. shopt -s checkwinsize               # update windows size on command
  786. shopt -s cmdhist                    # save multi-line commands in history as single line
  787. # shopt -s dotglob              # files beginning with . to be returned in the results of path-name expansion
  788. # shopt -s expand aliases           # expand aliases
  789. shopt -s extglob                # necessary for bash completion (programmable completion)
  790. # shopt -s globstar             # enables the ** globbing operator
  791. # shopt -s histappend               # bash history is only saved when close terminal, not after each command and this fixes it
  792. shopt -s histappend histreedit histverify
  793. # shopt -s histreedit
  794. # shopt -s histverify
  795. # shopt -s hostcomplete                 # attempt hostname expansion when @ is at the beginning of a word
  796. # shopt -s huponexit
  797. shopt -s mailwarn               # keep an eye on the mail file (access time)
  798. # shopt -s nocaseglob cdspell histappend
  799. shopt -s nocaseglob                 # pathname expansion will be treated as case-insensitive
  800. shopt -s no_empty_cmd_completion        # no empty completion (bash>=2.04 only)
  801. # shopt -s nullglob dotglob
  802. shopt -s sourcepath
  803. # shopt -u cmdhist              # do not treat multiple line commands as a single entry
  804. # shopt -u force_fignore            # expand to complete an ignored word, if no other words match.
  805. # shopt -u mailwarn
  806. # shopt -u sourcepath
  807. # stty -ixon                    # disable XON/XOFF flow control (^s/^q)
  808. stty start undef
  809. stty stop undef
  810. # stty stop ''                  # use C-s to search forward through history (do not block output)
  811. # ulimit -c unlimited               # let me have core dumps
  812. ulimit -S -c 0                      # (core file size) don't want any coredumps
  813. # ulimit -S -f 1024                 # open files
  814. # ulimit -S -s 8192                 # stack size
  815. # ulimit -S -u 256                  # max user processes
  816. # umask 007                     # all files created 660, dirs 770
  817. # umask 022                 # makes new files have permissions: rwxr-xr-x
  818. # umask 077                         # after everything is installed, uncomment this and the mkdir alias below ((base 8) 777 & ~077 = 700 = u=rwx,g=,o=)
  819. # unset HISTFILESIZE
  820. # unset HISTSIZE                # infinite History
  821. unset MAILCHECK                     # don't want my shell to warn me of incoming mail
  822. # unsetopt bgnice                       # don't nice bg command
  823.  
  824. if [ -d $HOME/Maildir/ ]; then
  825.     export MAIL=$HOME/Maildir/
  826.     export MAILPATH=$HOME/Maildir/
  827.     export MAILDIR=$HOME/Maildir/
  828. elif [ -f /var/mail/$USER ]; then
  829.     export MAIL="/var/mail/$USER"
  830. fi
  831.  
  832. if [ "$TERM" = "screen" ]; then
  833.     export TERM=$TERMINAL
  834. fi
  835.  
  836. # if [ "$OS" = "Linux" ]; then
  837. #     source ~/.lscolorsrc
  838. # elif [ "$OS" = "Darwin" ]; then
  839. #     export LSCOLORS='gxfxcxdxbxegedabagacad'
  840. # fi
  841.  
  842. function get_xserver()
  843. {
  844.     case $TERM in
  845.        xterm )
  846.             XSERVER=$(who am i | awk '{print $NF}' | tr -d ')''(' )
  847.             # Ane-Pieter Wieringa suggests the following alternative:
  848.             # I_AM=$(who am i)
  849.             # SERVER=${I_AM#*(}
  850.             # SERVER=${SERVER%*)}
  851.             XSERVER=${XSERVER%%:*}
  852.             ;;
  853.         aterm | rxvt)
  854.         # Find some code that works here. ...
  855.             ;;
  856.     esac
  857. }
  858. if [ -z ${DISPLAY:=""} ]; then
  859.     get_xserver
  860.     if [[ -z ${XSERVER}  || ${XSERVER} == $(hostname) || \
  861.       ${XSERVER} == "unix" ]]; then
  862.         DISPLAY=":0.0"          # Display on local host.
  863.     else
  864.         DISPLAY=${XSERVER}:0.0  # Display on remote host.
  865.     fi
  866. fi
  867. export DISPLAY
  868.  
  869. # if [ -f ~/.bash_exports ]; then . ~/.bash_exports ; fi
  870. # if [ -f ~/.bash_functions ]; then . ~/.bash_functions ; fi
  871. # if [ -f ~/.bash_aliases ]; then . ~/.bash_aliases ; fi
  872. # if [ -f ~/.bash_completion ]; then . ~/.bash_completion ; fi
  873. # if [ -f /etc/bash_completion ]; then . /etc/bash_completion ; complete -cf sudo; fi
  874.  
  875.  
  876.  
  877. ##################################################
  878. # Alternative To The "200 Lines Kernel Patch That#
  879. # Does Wonders"                  #
  880. ##################################################
  881.  
  882. ###### FOR DISTROS THAT USE '/cgroup/cpu' & '/etc/init.d/rc.local' (REDHAT/CENTOS?)
  883. # Run sudo gedit /etc/init.d/rc.local & add following lines above "exit 0":
  884. #   mkdir -p /cgroup/cpu
  885. #   mount -t cgroup cgroup /cgroup/cpu -o cpu
  886. #   mkdir -m 0777 /cgroup/cpu/user
  887. #   echo "/usr/local/sbin/cgroup_clean" > /cgroup/cpu/release_agent
  888. # Now, make it executable:
  889. # sudo chmod +x /etc/init.d/rc.local
  890. # To make sure that cgroups are deleted whenever the last task
  891. # leaves, run sudo gedit /usr/local/sbin/cgroup_clean and copy-paste this:
  892. #   #!/bin/sh
  893. #   if [ "$*" != "/user" ]; then
  894. #   rmdir /cgroup/cpu/$*
  895. #   fi
  896. # Now, make it executable:
  897. # sudo chmod +x /usr/local/sbin/cgroup_clean
  898. # Ensure the below ~/.bashrc section is uncommented
  899. # Restart your computer to apply the changes.
  900. #
  901. #
  902. #
  903. # BEFORE YOU UNCOMMENT THE BELOW, MAKE SURE YOU'VE DONE THE ABOVE
  904. #   if [ "$PS1" ] ; then
  905. #   mkdir -p -m 0700 /cgroup/cpu/user/$$ > /dev/null 2>&1
  906. #       echo $$ > /cgroup/cpu/user/$$/tasks
  907. #   echo "1" > /cgroup/cpu/user/$$/notify_on_release
  908. #   fi
  909.  
  910.  
  911.  
  912. ###### FOR DISTROS THAT USE '/sys/fs/cgroup/cpu' & '/etc/init.d/rc.local'
  913. # Run sudo gedit /etc/init.d/rc.local & add following lines above "exit 0":
  914. #   mkdir -p /sys/fs/cgroup/cpu
  915. #   mount -t cgroup cgroup /sys/fs/cgroup/cpu -o cpu
  916. #   mkdir -m 0777 /sys/fs/cgroup/cpu/user
  917. #   echo "/usr/local/sbin/cgroup_clean" > /sys/fs/cgroup/cpu/release_agent
  918. # Now, make it executable:
  919. # sudo chmod +x /etc/init.d/rc.local
  920. # To make sure that cgroups are deleted whenever the last task
  921. # leaves, run sudo gedit /usr/local/sbin/cgroup_clean and copy-paste this:
  922. #   #!/bin/sh
  923. #   if [ "$*" != "/user" ]; then
  924. #   rmdir /sys/fs/cgroup/cpu/$*
  925. #   fi
  926. # Now, make it executable:
  927. # sudo chmod +x /usr/local/sbin/cgroup_clean
  928. # Ensure the below ~/.bashrc section is uncommented
  929. # Restart your computer to apply the changes.
  930. #
  931. #
  932. #
  933. # BEFORE YOU UNCOMMENT THE BELOW, MAKE SURE YOU'VE DONE THE ABOVE
  934. #   if [ "$PS1" ] ; then
  935. #   mkdir -p -m 0700 /sys/fs/cgroup/cpu/user/$$ > /dev/null 2>&1
  936. #       echo $$ > /sys/fs/cgroup/cpu/user/$$/tasks
  937. #   echo "1" > /sys/fs/cgroup/cpu/user/$$/notify_on_release
  938. #   fi
  939.  
  940.  
  941.  
  942. ###### FOR UBUNTU (AND OTHER DISTROS THAT USE '/dev/cgroup/cpu' & '/etc/rc.local')
  943. # Run sudo gedit /etc/rc.local & add following lines above "exit 0":
  944. #   mkdir -p /dev/cgroup/cpu
  945. #   mount -t cgroup cgroup /dev/cgroup/cpu -o cpu
  946. #   mkdir -m 0777 /dev/cgroup/cpu/user
  947. #   echo "/usr/local/sbin/cgroup_clean" > /dev/cgroup/cpu/release_agent
  948. # Now, make it executable:
  949. # sudo chmod +x /etc/rc.local
  950. # To make sure that cgroups are deleted whenever the last task
  951. # leaves, run sudo gedit /usr/local/sbin/cgroup_clean and copy-paste this:
  952. #   #!/bin/sh
  953. #   if [ "$*" != "/user" ]; then
  954. #   rmdir /dev/cgroup/cpu/$*
  955. #   fi
  956. # Now, make it executable:
  957. # sudo chmod +x /usr/local/sbin/cgroup_clean
  958. # Ensure the below ~/.bashrc section is uncommented
  959. # Restart your computer to apply the changes.
  960. #
  961. #
  962. #
  963. # BEFORE YOU UNCOMMENT THE BELOW, MAKE SURE YOU'VE DONE THE ABOVE
  964. #    if [ "$PS1" ] ; then
  965. #   mkdir -p -m 0700 /dev/cgroup/cpu/user/$$ > /dev/null 2>&1
  966. #       echo $$ > /dev/cgroup/cpu/user/$$/tasks
  967. #       echo "1" > /dev/cgroup/cpu/user/$$/notify_on_release
  968. #    fi
  969.  
  970.  
  971.  
  972. ##################################################
  973. # PATH                       #
  974. ##################################################
  975.  
  976. if [ "$UID" -eq 0 ]; then
  977.     PATH=$PATH:/usr/local:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
  978. fi
  979.  
  980. # remove duplicate path entries
  981. export PATH=$(echo $PATH | awk -F: '
  982. { for (i = 1; i <= NF; i++) arr[$i]; }
  983. END { for (i in arr) printf "%s:" , i; printf "\n"; } ')
  984.  
  985. # autocomplete ssh commands
  986. complete -W "$(echo `cat ~/.bash_history | egrep '^ssh ' | sort | uniq | sed 's/^ssh //'`;)" ssh
  987.  
  988.  
  989.  
  990. ##################################################
  991. # Redirect bash built-in output to stdout    #
  992. ##################################################
  993.  
  994. # TIME=$( { time YOUR_COMMAND_HERE; } 2>&1 ) ; echo $TIME
  995.  
  996.  
  997.  
  998. ##################################################
  999. # Startup programs               #
  1000. ##################################################
  1001.  
  1002. # if [ "$USE_SCREEN" = "Y" ]; then
  1003. #     if [ "$UID" -ne 0 ]; then
  1004. #         if [ "$SHLVL" -eq 1 ]; then
  1005. #             /usr/bin/screen -d -RR
  1006. #         fi
  1007. #     fi
  1008. # fi
  1009.  
  1010. # if [ -e "/usr/games/fortune" ]; then
  1011. #     echo "Fortune: "
  1012. #     /usr/games/fortune
  1013. #     echo
  1014. # fi
  1015.  
  1016. # if [ -e "/usr/bin/uptime" ]; then
  1017. #     echo "Uptime: ` /usr/bin/uptime`"
  1018. # fi
  1019. # echo
  1020. # ~/bin/rc_sync.sh
  1021. # $HOME/bin/motd.pl
  1022.  
  1023.  
  1024.  
  1025. ##################################################
  1026. # Various options to make $HOME comfy        #
  1027. ##################################################
  1028.  
  1029. # if [ ! -d "${HOME}/bin" ]; then
  1030. #     mkdir ${HOME}/bin
  1031. #     chmod 700 ${HOME}/bin
  1032. #     echo "${HOME}/bin was missing.  I created it for you."
  1033. # fi
  1034.  
  1035. # if [ ! -d "${HOME}/Documents" ]; then
  1036. #     if ! [  -d "${HOME}/data" ]; then
  1037. #         mkdir ${HOME}/data
  1038. #         chmod 700 ${HOME}/data
  1039. #         echo "${HOME}/data was missing.  I created it for you."
  1040. #     fi
  1041. # fi
  1042.  
  1043. # if [ ! -d "${HOME}/tmp" ]; then
  1044. #     mkdir ${HOME}/tmp
  1045. #     chmod 700 ${HOME}/tmp
  1046. #     echo "${HOME}/tmp was missing.  I created it for you."
  1047. # fi
  1048.  
  1049.  
  1050.  
  1051. ##################################################
  1052. ##################################################
  1053. ##################################################
  1054.  
  1055.  
  1056.  
  1057.  
  1058.  
  1059.  
  1060.  
  1061.  
  1062. ######################################################################################################################################################
  1063. ###### COMPLETIONS ###### COMPLETIONS ###### COMPLETIONS ###### COMPLETIONS ###### COMPLETIONS ###### COMPLETIONS ###### COMPLETIONS ###### COMPLETIONS
  1064. ######################################################################################################################################################
  1065.  
  1066.  
  1067.  
  1068.  
  1069.  
  1070.  
  1071.  
  1072.  
  1073. ##################################################
  1074. # Completion functions (only since Bash-2.04)    #
  1075. ##################################################
  1076.  
  1077. ###### This is a 'universal' completion function - it works when commands have
  1078. # a so-called 'long options' mode , ie: 'ls --all' instead of 'ls -a'
  1079. # Needs the '-o' option of grep
  1080. # (try the commented-out version if not available).
  1081. # First, remove '=' from completion word separators
  1082. # (this will allow completions like 'ls --color=auto' to work correctly).
  1083.  
  1084.  
  1085.  
  1086. COMP_WORDBREAKS=${COMP_WORDBREAKS/=/}
  1087.  
  1088.  
  1089.  
  1090. ###### avoid tilde expansion from the bash_completion script
  1091. function _expand()
  1092. {
  1093.     [ "$cur" != "${cur%\\}" ] && cur="$cur\\";
  1094.    if [[ "$cur" == \~*/* ]]; then
  1095.        #eval cur=$cur;
  1096.         :;
  1097.    else
  1098.        if [[ "$cur" == \~* ]]; then
  1099.            cur=${cur#\~};
  1100.            COMPREPLY=($( compgen -P '~' -u $cur ));
  1101.            return ${#COMPREPLY[@]};
  1102.        fi;
  1103.    fi
  1104. }
  1105.  
  1106.  
  1107.  
  1108. function _get_longopts()
  1109. {
  1110.    # $1 --help | sed  -e '/--/!d' -e 's/.*--\([^[:space:].,]*\).*/--\1/'| \
  1111. # grep ^"$2" |sort -u ;
  1112.    $1 --help | grep -o -e "--[^[:space:].,]*" | grep -e "$2" |sort -u
  1113. }
  1114.  
  1115.  
  1116.  
  1117. function _killall()
  1118. {
  1119.    local cur prev
  1120.    COMPREPLY=()
  1121.    cur=${COMP_WORDS[COMP_CWORD]}
  1122.    # get a list of processes (the first sed evaluation
  1123.    # takes care of swapped out processes, the second
  1124.    # takes care of getting the basename of the process)
  1125.    COMPREPLY=( $( /usr/bin/ps -u $USER -o comm  | \
  1126.        sed -e '1,1d' -e 's#[]\[]##g' -e 's#^.*/##'| \
  1127.        awk '{if ($0 ~ /^'$cur'/) print $0}' ))
  1128.    return 0
  1129. }
  1130. complete -F _killall killall killps
  1131.  
  1132.  
  1133.  
  1134. function _longopts()
  1135. {
  1136.    local cur
  1137.    cur=${COMP_WORDS[COMP_CWORD]}
  1138.    case "${cur:-*}" in
  1139.       -*)      ;;
  1140.        *)      return ;;
  1141.    esac
  1142.    case "$1" in
  1143.      \~*)      eval cmd="$1" ;;
  1144.        *)      cmd="$1" ;;
  1145.    esac
  1146.    COMPREPLY=( $(_get_longopts ${1} ${cur} ) )
  1147. }
  1148. complete  -o default -F _longopts configure bash
  1149. complete  -o default -F _longopts wget id info a2ps ls recode
  1150.  
  1151.  
  1152.  
  1153. function _make()
  1154. {
  1155.    local mdef makef makef_dir="." makef_inc gcmd cur prev i;
  1156.    COMPREPLY=();
  1157.    cur=${COMP_WORDS[COMP_CWORD]};
  1158.    prev=${COMP_WORDS[COMP_CWORD-1]};
  1159.    case "$prev" in
  1160.        -*f)
  1161.            COMPREPLY=($(compgen -f $cur ));
  1162.            return 0
  1163.        ;;
  1164.    esac;
  1165.    case "$cur" in
  1166.        -*)
  1167.            COMPREPLY=($(_get_longopts $1 $cur ));
  1168.            return 0
  1169.        ;;
  1170.    esac;
  1171.    # make reads `GNUmakefile', then `makefile', then `Makefile'
  1172.    if [ -f ${makef_dir}/GNUmakefile ]; then
  1173.        makef=${makef_dir}/GNUmakefile
  1174.    elif [ -f ${makef_dir}/makefile ]; then
  1175.        makef=${makef_dir}/makefile
  1176.    elif [ -f ${makef_dir}/Makefile ]; then
  1177.        makef=${makef_dir}/Makefile
  1178.    else
  1179.        makef=${makef_dir}/*.mk        # Local convention.
  1180.    fi
  1181.    # Before we scan for targets, see if a Makefile name was
  1182.    # specified with -f ...
  1183.    for (( i=0; i < ${#COMP_WORDS[@]}; i++ )); do
  1184.        if [[ ${COMP_WORDS[i]} == -f ]]; then
  1185.           # eval for tilde expansion
  1186.           eval makef=${COMP_WORDS[i+1]}
  1187.           break
  1188.        fi
  1189.    done
  1190.    [ ! -f $makef ] && return 0
  1191.    # deal with included Makefiles
  1192.    makef_inc=$( grep -E '^-?include' $makef | \
  1193.    sed -e "s,^.* ,"$makef_dir"/," )
  1194.    for file in $makef_inc; do
  1195.        [ -f $file ] && makef="$makef $file"
  1196.    done
  1197.    # If we have a partial word to complete, restrict completions to
  1198.    # matches of that word.
  1199.    if [ -n "$cur" ]; then gcmd='grep "^$cur"' ; else gcmd=cat ; fi
  1200.    COMPREPLY=( $( awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ \
  1201.                                {split($1,A,/ /);for(i in A)print A[i]}' \
  1202.                                $makef 2>/dev/null | eval $gcmd  ))
  1203. }
  1204. complete -F _make -X '+($*|*.[cho])' make gmake pmake\
  1205.  
  1206.  
  1207.  
  1208. ###### A meta-command completion function for commands like sudo(8), which need to
  1209. # first complete on a command, then complete according to that command's own
  1210. # completion definition - currently not quite foolproof,
  1211. # but still quite useful (By Ian McDonald, modified by me).
  1212. function _meta_comp()
  1213. {
  1214.    local cur func cline cspec
  1215.    COMPREPLY=()
  1216.    cur=${COMP_WORDS[COMP_CWORD]}
  1217.    cmdline=${COMP_WORDS[@]}
  1218.    if [ $COMP_CWORD = 1 ]; then
  1219.         COMPREPLY=( $( compgen -c $cur ) )
  1220.    else
  1221.        cmd=${COMP_WORDS[1]}            # Find command.
  1222.        cspec=$( complete -p ${cmd} )   # Find spec of that command.
  1223.        # COMP_CWORD and COMP_WORDS() are not read-only,
  1224.        # so we can set them before handing off to regular
  1225.        # completion routine:
  1226.        # Get current command line minus initial command,
  1227.        cline="${COMP_LINE#$1 }"
  1228.        # split current command line tokens into array,
  1229.        COMP_WORDS=( $cline )
  1230.        # set current token number to 1 less than now.
  1231.        COMP_CWORD=$(( $COMP_CWORD - 1 ))
  1232.        # If current arg is empty, add it to COMP_WORDS array
  1233.        # (otherwise that information will be lost).
  1234.        if [ -z $cur ]; then COMP_WORDS[COMP_CWORD]=""  ; fi
  1235.        if [ "${cspec%%-F *}" != "${cspec}" ]; then
  1236.      # if -F then get function:
  1237.            func=${cspec#*-F }
  1238.            func=${func%% *}
  1239.            eval $func $cline   # Evaluate it.
  1240.        else
  1241.            func=$( echo $cspec | sed -e 's/^complete//' -e 's/[^ ]*$//' )
  1242.            COMPREPLY=( $( eval compgen $func $cur ) )
  1243.        fi
  1244.    fi
  1245. }
  1246. complete -o default -F _meta_comp nohup \
  1247. eval exec trace truss strace sotruss gdb
  1248. complete -o default -F _meta_comp command type which man nice time
  1249.  
  1250.  
  1251.  
  1252. function _tar()
  1253. {
  1254.    local cur ext regex tar untar
  1255.    COMPREPLY=()
  1256.    cur=${COMP_WORDS[COMP_CWORD]}
  1257.    # If we want an option, return the possible long options.
  1258.    case "$cur" in
  1259.        -*)     COMPREPLY=( $(_get_longopts $1 $cur ) ); return 0;;
  1260.    esac
  1261.    if [ $COMP_CWORD -eq 1 ]; then
  1262.        COMPREPLY=( $( compgen -W 'c t x u r d A' -- $cur ) )
  1263.        return 0
  1264.    fi
  1265.    case "${COMP_WORDS[1]}" in
  1266.        ?(-)c*f)
  1267.            COMPREPLY=( $( compgen -f $cur ) )
  1268.            return 0
  1269.            ;;
  1270.            +([^Izjy])f)
  1271.            ext='tar'
  1272.            regex=$ext
  1273.            ;;
  1274.        *z*f)
  1275.            ext='tar.gz'
  1276.            regex='t\(ar\.\)\(gz\|Z\)'
  1277.            ;;
  1278.        *[Ijy]*f)
  1279.            ext='t?(ar.)bz?(2)'
  1280.            regex='t\(ar\.\)bz2\?'
  1281.            ;;
  1282.        *)
  1283.            COMPREPLY=( $( compgen -f $cur ) )
  1284.            return 0
  1285.            ;;
  1286.    esac
  1287.    if [[ "$COMP_LINE" == tar*.$ext' '* ]]; then
  1288.        # Complete on files in tar file.
  1289.        #
  1290.        # Get name of tar file from command line.
  1291.        tar=$( echo "$COMP_LINE" | \
  1292.               sed -e 's|^.* \([^ ]*'$regex'\) .*$|\1|' )
  1293.        # Devise how to untar and list it.
  1294.        untar=t${COMP_WORDS[1]//[^Izjyf]/}
  1295.        COMPREPLY=( $( compgen -W "$( echo $( tar $untar $tar \
  1296.                    2>/dev/null ) )" -- "$cur" ) )
  1297.        return 0
  1298.  
  1299.    else
  1300.        # File completion on relevant files.
  1301.        COMPREPLY=( $( compgen -G $cur\*.$ext ) )
  1302.    fi
  1303.    return 0
  1304. }
  1305. complete -F _tar -o default tar
  1306.  
  1307.  
  1308.  
  1309. ##################################################
  1310. ##################################################
  1311. ##################################################
  1312.  
  1313.  
  1314.  
  1315.  
  1316.  
  1317.  
  1318.  
  1319.  
  1320. ######################################################################################################################################################
  1321. ###### FUNCTIONS ###### FUNCTIONS ###### FUNCTIONS ###### FUNCTIONS ###### FUNCTIONS ###### FUNCTIONS ###### FUNCTIONS ###### FUNCTIONS ###### FUNCTIONS
  1322. ######################################################################################################################################################
  1323.  
  1324.  
  1325.  
  1326.  
  1327.  
  1328.  
  1329.  
  1330.  
  1331. ##################################################
  1332. # Download all images from a 4chan thread    #
  1333. ##################################################
  1334.  
  1335. function 4chanimages()
  1336. {
  1337. curl -s http://boards.4chan.org/wg/|sed -r 's/.*href="([^"]*).*/\1\n/g'|grep images|xargs wget
  1338. }
  1339.  
  1340.  
  1341.  
  1342. ##################################################
  1343. # Add a function you've defined to .bashrc   #
  1344. ##################################################
  1345.  
  1346. function addfunction() { declare -f $1 >> ~/.bashrc ; }
  1347.  
  1348.  
  1349.  
  1350. ##################################################
  1351. # Show all strings (ASCII & Unicode) in a file   #
  1352. ##################################################
  1353.  
  1354. function allStrings() { cat "$1" | tr -d "\0" | strings ; }
  1355.  
  1356.  
  1357.  
  1358. ##################################################
  1359. # Miscellaneous Fun              #
  1360. ##################################################
  1361.  
  1362. ###### anagrams
  1363. function anagrams()
  1364. {
  1365. cat > "/tmp/anagrams.py" <<"End-of-message"
  1366. #!/usr/bin/python
  1367. infile = open ("/usr/share/dict/words", "r")
  1368. ## "dict" is a reserved word
  1369. words_in = infile.readlines()
  1370. scrambled = raw_input("Enter the scrambled word: ")
  1371. scrambled = scrambled.lower()
  1372. scrambled_list = list(scrambled)
  1373. scrambled_list.sort()
  1374. for word in words_in:
  1375.    word_list = list(word.strip().lower())
  1376.    word_list.sort()
  1377.    ## you don't really have to compare lengths when using lists as the
  1378.    ## extra compare takes about as long as finding the first difference
  1379.    if word_list == scrambled_list:
  1380.        print word, scrambled
  1381. End-of-message
  1382. chmod +x "/tmp/anagrams.py"
  1383. "/tmp/anagrams.py" "$1"
  1384. rm "/tmp/anagrams.py"
  1385. }
  1386.  
  1387.  
  1388.  
  1389. ###### fake error string
  1390. function error()
  1391. {
  1392. while true; do awk '{ print ; system("let R=$RANDOM%10; sleep $R") }' compiler.log; done
  1393. }
  1394.  
  1395.  
  1396.  
  1397. ###### stupid funny face
  1398. function funny_face() {
  1399.  _ret=$?; if test $_ret -ne 0; then echo "0_0->ret=$_ret"; set ?=$_ret; unset _ret; else echo "^_^"; fi
  1400. }
  1401.  
  1402.  
  1403.  
  1404. ###### pretend to be busy in office to enjoy a cup of coffee
  1405. function grepcolor()
  1406. {
  1407. cat /dev/urandom | hexdump -C | grep --color=auto "ca fe"
  1408. }
  1409.  
  1410.  
  1411.  
  1412. ###### a simple number guessing game
  1413. function hilow()
  1414. {
  1415. biggest=1000                            # maximum number possible
  1416. guess=0                                 # guessed by player
  1417. guesses=0                               # number of guesses made
  1418. number=$(( $$ % $biggest ))             # random number, 1 .. $biggest
  1419. while [ $guess -ne $number ] ; do
  1420.  echo -n "Guess? " ; read guess
  1421.  if [ "$guess" -lt $number ] ; then
  1422.    echo "... bigger!"
  1423.  elif [ "$guess" -gt $number ] ; then
  1424.    echo "... smaller!"
  1425.  fi
  1426.  guesses=$(( $guesses + 1 ))
  1427. done
  1428. echo "Right!! Guessed $number in $guesses guesses."
  1429. }
  1430.  
  1431.  
  1432.  
  1433. ###### watch the National debt clock
  1434. function natdebt()
  1435. {
  1436. watch -n 10 "wget -q http://www.brillig.com/debt_clock -O - | grep debtiv.gif | sed -e 's/.*ALT=\"//' -e 's/\".*//' -e 's/ //g'"
  1437. }
  1438.  
  1439.  
  1440.  
  1441. function oneliners()
  1442. {
  1443. w3m -dump_source http://www.onelinerz.net/random-one-liners/1/ | awk ' /.*<div id=\"oneliner_[0-9].*/ {while (! /\/div/ ) { gsub("\n", ""); getline; }; gsub (/<[^>][^>]*>/, "", $0); print $0}'
  1444. }
  1445.  
  1446.  
  1447.  
  1448. ###### random cowsay stuff
  1449. function random_cow()
  1450. {
  1451.  files=(/usr/share/cowsay/cows/*)
  1452.  printf "%s\n" "${files[RANDOM % ${#files}]}"
  1453. }
  1454.  
  1455.  
  1456.  
  1457. ##################################################
  1458. # Temporarily add to PATH            #
  1459. ##################################################
  1460.  
  1461. function apath()
  1462. {
  1463.    if [ $# -lt 1 ] || [ $# -gt 2 ]; then
  1464.        echo "Temporarily add to PATH"
  1465.        echo "usage: apath [dir]"
  1466.    else
  1467.        PATH=$1:$PATH
  1468.    fi
  1469. }
  1470.  
  1471.  
  1472.  
  1473. ##################################################
  1474. # Function you want after you've overwritten some#
  1475. # important file using > instead of >> ^^    #
  1476. ##################################################
  1477.  
  1478. function append() {
  1479.        lastarg="${!#}"
  1480.        echo "${@:1:$(($#-1))}" >> "$lastarg"
  1481. }
  1482.  
  1483.  
  1484.  
  1485. ##################################################
  1486. # Common commands piped through grep         #
  1487. ##################################################
  1488.  
  1489. function aptg()     # debian specific.
  1490. {
  1491.    if [ $# -lt 1 ] || [ $# -gt 1 ]; then
  1492.        echo "search debian package list"
  1493.        echo "usage: aptg [program/keyword]"
  1494.    else
  1495.        apt-cache search $1 | sort | less
  1496.    fi
  1497. }
  1498.  
  1499.  
  1500.  
  1501. ###### grep by paragraph instead of by line
  1502. function grepp() { [ $# -eq 1 ] && perl -00ne "print if /$1/i" || perl -00ne "print if /$1/i" < "$2";}
  1503.  
  1504.  
  1505.  
  1506. function hgg()
  1507. {
  1508.    if [ $# -lt 1 ] || [ $# -gt 1 ]; then
  1509.        echo "search bash history"
  1510.        echo "usage: mg [search pattern]"
  1511.    else
  1512.        history | grep -i $1 | grep -v hg
  1513.    fi
  1514. }
  1515.  
  1516.  
  1517.  
  1518. function lsofg()
  1519. {
  1520.    if [ $# -lt 1 ] || [ $# -gt 1 ]; then
  1521.        echo "grep lsof"
  1522.        echo "usage: losfg [port/program/whatever]"
  1523.    else
  1524.        lsof | grep -i $1 | less
  1525.    fi
  1526. }
  1527.  
  1528.  
  1529.  
  1530. function psg()
  1531. {
  1532.    if [ $# -lt 1 ] || [ $# -gt 1 ]; then
  1533.        echo "grep running processes"
  1534.        echo "usage: psg [process]"
  1535.    else
  1536.        ps aux | grep USER | grep -v grep
  1537.        ps aux | grep -i $1 | grep -v grep
  1538.    fi
  1539. }
  1540.  
  1541.  
  1542.  
  1543. ##################################################
  1544. # Sudo stuff                     #
  1545. ##################################################
  1546.  
  1547. ###### Apt-get via sudo
  1548. # An apt-get wrapper function which will run the command via sudo, but will run it normally if you're only downloading source files.
  1549. # function apt-get() { [ "$1" = source ] && (command apt-get "$@";true) || sudo apt-get "$@" }
  1550.  
  1551.  
  1552.  
  1553. # function sudo()
  1554. # {
  1555. #   command="$@"
  1556. #   if [ -z "$command" ]; then
  1557. #     command sudo -s
  1558. #   else
  1559. #      command sudo "$@"
  1560. #   fi
  1561. # }
  1562.  
  1563.  
  1564.  
  1565. ###### Wrap sudo to handle aliases and functions
  1566. # (enabled means all 'sudo' in this file need
  1567. # to be removed) (disabled for now by adding
  1568. # a single '#')
  1569. # function sudo()
  1570. # {
  1571. # local c o t parse
  1572. ## Parse sudo args
  1573. # OPTIND=1
  1574. # while getopts xVhlLvkKsHPSb:p:c:a:u: t; do
  1575. # if [ "$t" = x ]; then
  1576. # parse=true
  1577. # else
  1578. # o="$o -$t"
  1579. # [ "$OPTARG" ] && o="$o $OPTARG"
  1580. # fi
  1581. # done
  1582. # shift $(( $OPTIND - 1 ))
  1583. ## If no arguments are left, it's a simple call to sudo
  1584. # if [ $#  -ge 1 ]; then
  1585. # c="$1";
  1586. # shift;
  1587. # case $(type -t "$c") in
  1588. # "")
  1589. # echo No such command "$c"
  1590. # return 127
  1591. # ;;
  1592. # alias)
  1593. # c="$(type "$c"|sed "s/^.* to \`//;s/.$//")"
  1594. # ;;
  1595. # function)
  1596. # c=$(type "$c"|sed 1d)";\"$c\""
  1597. # ;;
  1598. # *)
  1599. # c="\"$c\""
  1600. # ;;
  1601. # esac
  1602. # if [ -n "$parse" ]; then
  1603. ## Quote the rest once, so it gets processed by bash.
  1604. ## Done this way so variables can get expanded.
  1605. # while [ -n "$1" ]; do
  1606. # c="$c \"$1\""
  1607. # shift
  1608. # done
  1609. # else
  1610. ## Otherwise, quote the arguments. The echo gets an extra
  1611. ## space to prevent echo from parsing arguments like -n
  1612. ## Note the lovely interactions between " and ' ;-)
  1613. # while [ -n "$1" ]; do
  1614. # c="$c '$(echo " $1"|sed -e "s/^ //" -e "s/'/'\"'\"'/")'"
  1615. # shift
  1616. # done
  1617. # fi
  1618. ## Run the command with verbose options
  1619. ## echo Executing sudo $o -- bash -x -v -c "$c" >&2
  1620. # command sudo $o bash -xvc "$c"
  1621. # else
  1622. ## echo sudo $o >&2
  1623. # command sudo $o
  1624. # fi
  1625. # }
  1626.  
  1627.  
  1628.  
  1629. ###### Sudo for entire line (including pipes and redirects)
  1630. # USAGE: $ sudor your command
  1631. # This command uses a dirty hack with history, so be sure you not turned it off.
  1632. # WARNING!: This command behavior differ from other commands. It more like text macro, so you shouldn't use it in subshells, non-interactive sessions, other # functions/aliases and so on. You shouldn't pipe into sudor (any string that prefixes sudor will be removed), but if you really want, use this commands:
  1633. function proceed_sudo() { sudor_command="`HISTTIMEFORMAT=\"\" history 1 | sed -r -e 's/^.*?sudor//' -e 's/\"/\\\"/g'`" ; sudo sh -c "$sudor_command"; }; alias sudor="proceed_sudo # "
  1634.  
  1635.  
  1636.  
  1637. ##################################################
  1638. # To show Apt Log History            #
  1639. ##################################################
  1640.  
  1641. function apt-history() {
  1642.       case "$1" in
  1643.         install)
  1644.               cat /var/log/dpkg.log | grep 'install '
  1645.               ;;
  1646.         upgrade|remove)
  1647.               cat /var/log/dpkg.log | grep $1
  1648.               ;;
  1649.         rollback)
  1650.               cat /var/log/dpkg.log | grep upgrade | \
  1651.                   grep "$2" -A10000000 | \
  1652.                   grep "$3" -B10000000 | \
  1653.                   awk '{print $4"="$5}'
  1654.               ;;
  1655.         *)
  1656.               cat /var/log/dpkg.log
  1657.               ;;
  1658.       esac
  1659. }
  1660.  
  1661.  
  1662.  
  1663. ##################################################
  1664. # Undo apt-get build-dep (remove build       #
  1665. # dependencies)                  #
  1666. ##################################################
  1667.  
  1668. function aptitude-remove-dep() { sudo aptitude markauto $(apt-cache showsrc "$1" | grep Build-Depends | perl -p -e 's/(?:[\[(].+?[\])]|Build-Depends:|,|\|)//g'); }
  1669.  
  1670.  
  1671.  
  1672. ##################################################
  1673. # Arch-wiki-docs simple search           #
  1674. ##################################################
  1675.  
  1676. function archwikisearch() {
  1677.     # old version
  1678.     # cd /usr/share/doc/arch-wiki/html/
  1679.     # grep -i "$1" index.html | sed 's/.*HREF=.\(.*\.html\).*/\1/g' | xargs opera -newpage
  1680.     cd /usr/share/doc/arch-wiki/html/
  1681.     for i in $(grep -li $1 *)
  1682.     do
  1683.         STRING=`grep -m1 -o 'wgTitle = "[[:print:]]\+"' $i`
  1684.         LEN=${#STRING}
  1685.         let LEN=LEN-12
  1686.         STRING=${STRING:11:LEN}
  1687.         LOCATION="/usr/share/doc/arch-wiki/html/$i"
  1688.         echo -e " \E[33m$STRING   \E[37m$LOCATION"
  1689.     done
  1690. }
  1691.  
  1692.  
  1693.  
  1694. ##################################################
  1695. # Numerical conversions and numbers stuff    #
  1696. ##################################################
  1697.  
  1698. ###### convert arabic to roman numerals
  1699. # Copyright 2007 - 2010 Christopher Bratusek
  1700. function arabic2roman() {
  1701.  
  1702.   echo $1 | sed -e 's/1...$/M&/;s/2...$/MM&/;s/3...$/MMM&/;s/4...$/MMMM&/
  1703. s/6..$/DC&/;s/7..$/DCC&/;s/8..$/DCCC&/;s/9..$/CM&/
  1704. s/1..$/C&/;s/2..$/CC&/;s/3..$/CCC&/;s/4..$/CD&/;s/5..$/D&/
  1705. s/6.$/LX&/;s/7.$/LXX&/;s/8.$/LXXX&/;s/9.$/XC&/
  1706. s/1.$/X&/;s/2.$/XX&/;s/3.$/XXX&/;s/4.$/XL&/;s/5.$/L&/
  1707. s/1$/I/;s/2$/II/;s/3$/III/;s/4$/IV/;s/5$/V/
  1708. s/6$/VI/;s/7$/VII/;s/8$/VIII/;s/9$/IX/
  1709. s/[0-9]//g'
  1710.  
  1711. }
  1712.  
  1713.  
  1714.  
  1715. ###### convert ascii
  1716. # copyright 2007 - 2010 Christopher Bratusek
  1717. function asc2all() {
  1718.     if [[ $1 ]]; then
  1719.         echo "ascii $1 = binary $(asc2bin $1)"
  1720.         echo "ascii $1 = octal $(asc2oct $1)"
  1721.         echo "ascii $1 = decimal $(asc2dec $1)"
  1722.         echo "ascii $1 = hexadecimal $(asc2hex $1)"
  1723.         echo "ascii $1 = base32 $(asc2b32 $1)"
  1724.         echo "ascii $1 = base64 $(asc2b64 $1)"
  1725.     fi
  1726. }
  1727.  
  1728.  
  1729.  
  1730. function asc2bin() {
  1731.     if [[ $1 ]]; then
  1732.         echo "obase=2 ; $(asc2dec $1)" | bc
  1733.     fi
  1734. }
  1735.  
  1736.  
  1737.  
  1738. function asc2b64() {
  1739.     if [[ $1 ]]; then
  1740.         echo "obase=64 ; $(asc2dec $1)" | bc
  1741.     fi
  1742. }
  1743.  
  1744.  
  1745.  
  1746. function asc2b32() {
  1747.     if [[ $1 ]]; then
  1748.         echo "obase=32 ; $(asc2dec $1)" | bc
  1749.     fi
  1750. }
  1751.  
  1752.  
  1753.  
  1754. function asc2dec() {
  1755.     if [[ $1 ]]; then
  1756.         printf '%d\n' "'$1'"
  1757.     fi
  1758. }
  1759.  
  1760.  
  1761.  
  1762. function asc2hex() {
  1763.     if [[ $1 ]]; then
  1764.         echo "obase=16 ; $(asc2dec $1)" | bc
  1765.     fi
  1766. }
  1767.  
  1768.  
  1769.  
  1770. function asc2oct() {
  1771.     if [[ $1 ]]; then
  1772.         echo "obase=8 ; $(asc2dec $1)" | bc
  1773.     fi
  1774. }
  1775.  
  1776.  
  1777.  
  1778. ###### Averaging columns of numbers
  1779. # Computes a columns average in a file. Input parameters = column number and optional pattern.
  1780. function avg() { awk "/$2/{sum += \$$1; lc += 1;} END {printf \"Average over %d lines: %f\n\", lc, sum/lc}"; }
  1781.  
  1782.  
  1783.  
  1784. ###### convert binaries
  1785. # copyright 2007 - 2010 Christopher Bratusek
  1786. function bin2all() {
  1787.     if [[ $1 ]]; then
  1788.         echo "binary $1 = octal $(bin2oct $1)"
  1789.         echo "binary $1 = decimal $(bin2dec $1)"
  1790.         echo "binary $1 = hexadecimal $(bin2hex $1)"
  1791.         echo "binary $1 = base32 $(bin2b32 $1)"
  1792.         echo "binary $1 = base64 $(bin2b64 $1)"
  1793.         echo "binary $1 = ascii $(bin2asc $1)"
  1794.     fi
  1795. }
  1796.  
  1797.  
  1798.  
  1799. function bin2asc() {
  1800.     if [[ $1 ]]; then
  1801.         echo -e "\0$(printf %o $((2#$1)))"
  1802.     fi
  1803. }
  1804.  
  1805.  
  1806.  
  1807. function bin2b64() {
  1808.     if [[ $1 ]]; then
  1809.         echo "obase=64 ; ibase=2 ; $1" | bc
  1810.     fi
  1811. }
  1812.  
  1813.  
  1814.  
  1815. function bin2b32() {
  1816.     if [[ $1 ]]; then
  1817.         echo "obase=32 ; ibase=2 ; $1 " | bc
  1818.     fi
  1819. }
  1820.  
  1821.  
  1822.  
  1823. function bin2dec() {
  1824.     if [[ $1 ]]; then
  1825.         echo $((2#$1))
  1826.     fi
  1827. }
  1828.  
  1829.  
  1830.  
  1831. function bin2hex() {
  1832.     if [[ $1 ]]; then
  1833.         echo "obase=16 ; ibase=2 ; $1" | bc
  1834.     fi
  1835. }
  1836.  
  1837.  
  1838.  
  1839. function bin2oct() {
  1840.     if [[ $1 ]]; then
  1841.         echo "obase=8 ; ibase=2 ; $1" | bc
  1842.     fi
  1843. }
  1844.  
  1845.  
  1846.  
  1847. ###### simple calculator to 4 decimals
  1848. function calc() {
  1849. echo "scale=4; $1" | bc
  1850. }
  1851.  
  1852.  
  1853.  
  1854. ###### temperature conversion
  1855. # Copyright 2007 - 2010 Christopher Bratusek
  1856. function cel2fah() {
  1857.  
  1858.   if [[ $1 ]]; then
  1859.     echo "scale=2; $1 * 1.8  + 32" | bc
  1860.   fi
  1861.  
  1862. }
  1863.  
  1864.  
  1865.  
  1866. function cel2kel() {
  1867.  
  1868.   if [[ $1 ]]; then
  1869.     echo "scale=2; $1 + 237.15" | bc
  1870.   fi
  1871.  
  1872. }
  1873.  
  1874.  
  1875.  
  1876. function fah2cel() {
  1877.  
  1878.   if [[ $1 ]]; then
  1879.     echo "scale=2 ; ( $1 - 32  ) / 1.8" | bc
  1880.   fi
  1881.  
  1882. }
  1883.  
  1884.  
  1885.  
  1886. function fah2kel() {
  1887.  
  1888.   if [[ $1 ]]; then
  1889.     echo "scale=2; ( $1 + 459.67 ) / 1.8 " | bc
  1890.   fi
  1891.  
  1892. }
  1893.  
  1894.  
  1895.  
  1896. function kel2cel() {
  1897.  
  1898.   if [[ $1 ]]; then
  1899.     echo "scale=2; $1 - 273.15" | bc
  1900.   fi
  1901.  
  1902. }
  1903.  
  1904.  
  1905.  
  1906. function kel2fah() {
  1907.  
  1908.   if [[ $1 ]]; then
  1909.     echo "scale=2; $1 * 1.8 - 459,67" | bc
  1910.   fi
  1911.  
  1912. }
  1913.  
  1914.  
  1915.  
  1916. ###### Output an ASCII character given its decimal equivalent
  1917. function chr() { printf \\$(($1/64*100+$1%64/8*10+$1%8)); }
  1918.  
  1919.  
  1920.  
  1921. ###### the notorious "hailstone" or Collatz series.
  1922. function collatz()
  1923. {
  1924. # get the integer "seed" from the command-line to generate the integer "result"
  1925. # if NUMBER is even, divide by 2, or if odd, multiply by 3 and add 1
  1926. # the theory is that every sequence eventually settles down to repeating "4,2,1..." cycles
  1927. MAX_ITERATIONS=200
  1928. # For large seed numbers (>32000), try increasing MAX_ITERATIONS.
  1929. h=${1:-$$}                      #  Seed. #  Use $PID as seed, #+ if not specified as command-line arg.
  1930. echo
  1931. echo "C($h) --- $MAX_ITERATIONS Iterations"
  1932. echo
  1933. for ((i=1; i<=MAX_ITERATIONS; i++))
  1934. do
  1935. COLWIDTH=%7d
  1936. printf $COLWIDTH $h
  1937.   let "remainder = h % 2"
  1938.   if [ "$remainder" -eq 0 ]   # Even?
  1939.   then
  1940.     let "h /= 2"              # Divide by 2.
  1941.   else
  1942.     let "h = h*3 + 1"         # Multiply by 3 and add 1.
  1943.   fi
  1944. COLUMNS=10                    # Output 10 values per line.
  1945. let "line_break = i % $COLUMNS"
  1946. if [ "$line_break" -eq 0 ]
  1947. then
  1948.   echo
  1949. fi
  1950. done
  1951. echo
  1952. }
  1953.  
  1954.  
  1955.  
  1956. ###### temperature conversion script that lets the user enter
  1957. # a temperature in any of Fahrenheit, Celsius or Kelvin and receive the
  1958. # equivalent temperature in the other two units as the output.
  1959. # usage:    convertatemp F100 (if don't put F,C, or K, default is F)
  1960. function convertatemp()
  1961. {
  1962. if uname | grep 'SunOS'>/dev/null ; then
  1963.   echo "Yep, SunOS, let\'s fix this baby"
  1964.   PATH="/usr/xpg4/bin:$PATH"
  1965. fi
  1966. if [ $# -eq 0 ] ; then
  1967.   cat << EOF >&2
  1968. Usage: $0 temperature[F|C|K]
  1969. where the suffix:
  1970.    F    indicates input is in Fahrenheit (default)
  1971.    C    indicates input is in Celsius
  1972.    K    indicates input is in Kelvin
  1973. EOF
  1974. fi
  1975. unit="$(echo $1|sed -e 's/[-[[:digit:]]*//g' | tr '[:lower:]' '[:upper:]' )"
  1976. temp="$(echo $1|sed -e 's/[^-[[:digit:]]*//g')"
  1977. case ${unit:=F}
  1978. in
  1979.   F ) # Fahrenheit to Celsius formula:  Tc = (F -32 ) / 1.8
  1980.   farn="$temp"
  1981.   cels="$(echo "scale=2;($farn - 32) / 1.8" | bc)"
  1982.  kelv="$(echo "scale=2;$cels + 273.15" | bc)"
  1983.  ;;
  1984.  C ) # Celsius to Fahrenheit formula: Tf = (9/5)*Tc+32
  1985.  cels=$temp
  1986.  kelv="$(echo "scale=2;$cels + 273.15" | bc)"
  1987.  farn="$(echo "scale=2;((9/5) * $cels) + 32" | bc)"
  1988.  ;;
  1989.  K ) # Celsius = Kelvin + 273.15, then use Cels -> Fahr formula
  1990.  kelv=$temp
  1991.  cels="$(echo "scale=2; $kelv - 273.15" | bc)"
  1992.  farn="$(echo "scale=2; ((9/5) * $cels) + 32" | bc)"
  1993. esac
  1994. echo "Fahrenheit = $farn"
  1995. echo "Celsius    = $cels"
  1996. echo "Kelvin     = $kelv"
  1997. }
  1998.  
  1999.  
  2000.  
  2001. ###### convert hexadecimal numbers to decimals
  2002. function dec()      { printf "%d\n" $1; }
  2003.  
  2004.  
  2005.  
  2006. ###### convert decimals to hexadecimal numbers
  2007. function hex()      { printf "0x%08x\n" $1; }
  2008.  
  2009.  
  2010.  
  2011. ###### convert decimals
  2012. # copyright 2007 - 2010 Christopher Bratusek
  2013. function dec2all() {
  2014.     if [[ $1 ]]; then
  2015.         echo "decimal $1 = binary $(dec2bin $1)"
  2016.         echo "decimal $1 = octal $(dec2oct $1)"
  2017.         echo "decimal $1 = hexadecimal $(dec2hex $1)"
  2018.         echo "decimal $1 = base32 $(dec2b32 $1)"
  2019.         echo "decimal $1 = base64 $(dec2b64 $1)"
  2020.         echo "deciaml $1 = ascii $(dec2asc $1)"
  2021.     fi
  2022. }
  2023.  
  2024.  
  2025.  
  2026. function dec2asc() {
  2027.     if [[ $1 ]]; then
  2028.         echo -e "\0$(printf %o 97)"
  2029.     fi
  2030. }
  2031.  
  2032.  
  2033.  
  2034. function dec2bin() {
  2035.     if [[ $1 ]]; then
  2036.         echo "obase=2 ; $1" | bc
  2037.     fi
  2038. }
  2039.  
  2040.  
  2041.  
  2042. function dec2b64() {
  2043.     if [[ $1 ]]; then
  2044.         echo "obase=64 ; $1" | bc
  2045.     fi
  2046. }
  2047.  
  2048.  
  2049.  
  2050. function dec2b32() {
  2051.     if [[ $1 ]]; then
  2052.         echo "obase=32 ; $1" | bc
  2053.     fi
  2054. }
  2055.  
  2056.  
  2057.  
  2058. function dec2hex() {
  2059.     if [[ $1 ]]; then
  2060.         echo "obase=16 ; $1" | bc
  2061.     fi
  2062. }
  2063.  
  2064.  
  2065.  
  2066. function dec2oct() {
  2067.     if [[ $1 ]]; then
  2068.         echo "obase=8 ; $1" | bc
  2069.     fi
  2070. }
  2071.  
  2072.  
  2073.  
  2074. ###### number --- convert decimal integer to english words
  2075. # total number
  2076. # Usage:    dec2text 1234 -> one thousand two hundred thirty-four
  2077. # Author: Noah Friedman <friedman@prep.ai.mit.edu>
  2078. function dec2text()
  2079. {
  2080. prog=`echo "$0" | sed -e 's/[^\/]*\///g'`
  2081. garbage=`echo "$*" | sed -e 's/[0-9,.]//g'`
  2082. if test ".$garbage" != "."; then
  2083.  echo "$prog: Invalid character in argument." 1>&2
  2084. fi
  2085. case "$*" in
  2086. # This doesn't always seem to work.
  2087. #   *[!0-9,.]* ) echo "$prog: Invalid character in argument." 1>&2; ;;
  2088.   *.* ) echo "$prog: fractions not supported (yet)." 1>&2; ;;
  2089.   '' ) echo "Usage: $prog [decimal integer]" 1>&2; ;;
  2090. esac
  2091. result=
  2092. eval set - "`echo ${1+\"$@\"} | sed -n -e '
  2093.  s/[, ]//g
  2094.  s/^00*/0/g
  2095.  s/\(.\)\(.\)\(.\)$/\"\1 \2 \3\"/
  2096.  :l
  2097.  /[0-9][0-9][0-9]/{
  2098.     s/\([^\" ][^\" ]*\)\([^\" ]\)\([^\" ]\)\([^\" ]\)/\1\"\2 \3 \4\"/g
  2099.     t l
  2100.  }
  2101.  /^[0-9][0-9][0-9]/s/\([^\" ]\)\([^\" ]\)\([^\" ]\)/\"\1 \2 \3\"/
  2102.  /^[0-9][0-9]/s/\([^\" ]\)\([^\" ]\)/\"\1 \2\"/
  2103.  /^[0-9]/s/^\([^\" ][^\" ]*\)/\"\1\"/g;s/\"\"/\" \"/g
  2104.  p'`"
  2105. while test $# -ne 0 ; do
  2106.  eval `set - $1;
  2107.        d3='' d2='' d1=''
  2108.        case $# in
  2109.          1 ) d1=$1 ;;
  2110.          2 ) d2=$1 d1=$2 ;;
  2111.          3 ) d3=$1 d2=$2 d1=$3 ;;
  2112.        esac
  2113.        echo "d3=\"$d3\" d2=\"$d2\" d1=\"$d1\""`
  2114.  val1='' val2='' val3=''
  2115.  case "$d3" in
  2116.    1 ) val3=one   ;;     6 ) val3=six   ;;
  2117.    2 ) val3=two   ;;     7 ) val3=seven ;;
  2118.    3 ) val3=three ;;     8 ) val3=eight ;;
  2119.    4 ) val3=four  ;;     9 ) val3=nine  ;;
  2120.    5 ) val3=five  ;;
  2121.  esac
  2122.  case "$d2" in
  2123.    1 ) val2=teen   ;;    6 ) val2=sixty   ;;
  2124.    2 ) val2=twenty ;;    7 ) val2=seventy ;;
  2125.    3 ) val2=thirty ;;    8 ) val2=eighty  ;;
  2126.    4 ) val2=forty  ;;    9 ) val2=ninety  ;;
  2127.    5 ) val2=fifty  ;;
  2128.  esac
  2129.  case "$val2" in
  2130.    teen )
  2131.      val2=
  2132.      case "$d1" in
  2133.        0 ) val1=ten      ;;     5 ) val1=fifteen   ;;
  2134.        1 ) val1=eleven   ;;     6 ) val1=sixteen   ;;
  2135.        2 ) val1=twelve   ;;     7 ) val1=seventeen ;;
  2136.        3 ) val1=thirteen ;;     8 ) val1=eighteen  ;;
  2137.        4 ) val1=fourteen ;;     9 ) val1=nineteen  ;;
  2138.      esac
  2139.     ;;
  2140.    0 ) : ;;
  2141.    * )
  2142.      test ".$val2" != '.' -a ".$d1" != '.0' \
  2143.       && val2="${val2}-"
  2144.      case "$d1" in
  2145.        0 ) val2="$val2 " ;;     5 ) val1=five  ;;
  2146.        1 ) val1=one      ;;     6 ) val1=six   ;;
  2147.        2 ) val1=two      ;;     7 ) val1=seven ;;
  2148.        3 ) val1=three    ;;     8 ) val1=eight ;;
  2149.        4 ) val1=four     ;;     9 ) val1=nine  ;;
  2150.      esac
  2151.     ;;
  2152.  esac
  2153.  test ".$val3" != '.' && result="$result$val3 hundred "
  2154.  test ".$val2" != '.' && result="$result$val2"
  2155.  test ".$val1" != '.' && result="$result$val1 "
  2156.  if test ".$d1$d2$d3" != '.000' ; then
  2157.    case $# in
  2158.       0 | 1 ) ;;
  2159.       2 ) result="${result}thousand "          ;;
  2160.       3 ) result="${result}million "           ;;
  2161.       4 ) result="${result}billion "           ;;
  2162.       5 ) result="${result}trillion "          ;;
  2163.       6 ) result="${result}quadrillion "       ;;
  2164.       7 ) result="${result}quintillion "       ;;
  2165.       8 ) result="${result}sextillion "        ;;
  2166.       9 ) result="${result}septillion "        ;;
  2167.      10 ) result="${result}octillion "         ;;
  2168.      11 ) result="${result}nonillion "         ;;
  2169.      12 ) result="${result}decillion "         ;;
  2170.      13 ) result="${result}undecillion "       ;;
  2171.      14 ) result="${result}duodecillion "      ;;
  2172.      15 ) result="${result}tredecillion "      ;;
  2173.      16 ) result="${result}quattuordecillion " ;;
  2174.      17 ) result="${result}quindecillion "     ;;
  2175.      18 ) result="${result}sexdecillion "      ;;
  2176.      19 ) result="${result}septendecillion "   ;;
  2177.      20 ) result="${result}octodecillion "     ;;
  2178.      21 ) result="${result}novemdecillion "    ;;
  2179.      22 ) result="${result}vigintillion "      ;;
  2180.      * ) echo "Error: number too large (66 digits max)." 1>&2; ;;
  2181.    esac
  2182.  fi
  2183.  shift
  2184. done
  2185. set $result > /dev/null
  2186. case "$*" in
  2187.  '') set zero ;;
  2188. esac
  2189. echo ${1+"$@"}
  2190. # number ends here
  2191. }
  2192.  
  2193.  
  2194.  
  2195. # individual numbers
  2196. # Usage:    dec2text 1234 -> one two three four
  2197. function dec2text_()
  2198. {
  2199. # This script is part of nixCraft shell script collection (NSSC)
  2200. # Visit http://bash.cyberciti.biz/ for more information.
  2201. n=$1
  2202. len=$(echo $n | wc -c)
  2203. len=$(( $len - 1 ))
  2204. for (( i=1; i<=$len; i++ ))
  2205. do
  2206.   # get one digit at a time
  2207.    digit=$(echo $n | cut -c $i)
  2208.   # use case control structure to find digit equivalent in words
  2209.    case $digit in
  2210.        0) echo -n "zero " ;;
  2211.        1) echo -n "one " ;;
  2212.        2) echo -n "two " ;;
  2213.        3) echo -n "three " ;;
  2214.        4) echo -n "four " ;;
  2215.        5) echo -n "five " ;;
  2216.        6) echo -n "six " ;;
  2217.        7) echo -n "seven " ;;
  2218.        8) echo -n "eight " ;;
  2219.        9) echo -n "nine " ;;
  2220.    esac
  2221. done
  2222. # just print new line
  2223. echo ""
  2224. }
  2225.  
  2226.  
  2227.  
  2228. function d2u() {
  2229.     # copyright 2007 - 2010 Christopher Bratusek
  2230.     if [[ -e "$1" ]]; then
  2231.         sed -r 's/\r$//' -i "$1"
  2232.     fi
  2233. }
  2234.  
  2235.  
  2236.  
  2237. function u2d() {
  2238.     # copyright 2007 - 2010 Christopher Bratusek
  2239.     if [[ -e "$1" ]]; then
  2240.         sed -r 's/$/\r/' -i "$1"
  2241.     fi
  2242. }
  2243.  
  2244.  
  2245.  
  2246. ###### factorial for integers
  2247. function factorial()
  2248. {
  2249. echo "Enter an integer: "
  2250. read n
  2251. # Below we define the factorial function in bc syntax
  2252. fact="define f (x) {
  2253. i=x
  2254. fact=1
  2255. while (i > 1) {
  2256. fact=fact*i
  2257. i=i-1
  2258. }
  2259. return fact
  2260. }"
  2261. # Below we pass the function defined above, and call it with n as a parameter and pipe it to bc
  2262. factorial=`echo "$fact;f($n)" | bc -l`
  2263. echo "$n! = $factorial"
  2264. }
  2265.  
  2266.  
  2267.  
  2268. ###### convert hexadecimal numbers
  2269. # copyright 2007 - 2010 Christopher Bratusek
  2270. function hex2all() {
  2271.     if [[ $1 ]]; then
  2272.         echo "hexadecimal $1 = binary $(hex2bin $1)"
  2273.         echo "hexadecimal $1 = octal $(hex2oct $1)"
  2274.         echo "hexadecimal $1 = decimal $(hex2dec $1)"
  2275.         echo "hexadecimal $1 = base32 $(hex2b32 $1)"
  2276.         echo "hexadecimal $1 = base64 $(hex2b64 $1)"
  2277.         echo "hexadecimal $1 = ascii $(hex2asc $1)"
  2278.     fi
  2279. }
  2280.  
  2281.  
  2282.  
  2283. function hex2asc() {
  2284.     if [[ $1 ]]; then
  2285.         echo -e "\0$(printf %o $((16#$1)))"
  2286.     fi
  2287. }
  2288.  
  2289.  
  2290.  
  2291. function hex2bin() {
  2292.     if [[ $1 ]]; then
  2293.         echo "obase=2 ; ibase=16 ; $1" | bc
  2294.     fi
  2295. }
  2296.  
  2297.  
  2298.  
  2299. function hex2b64() {
  2300.     if [[ $1 ]]; then
  2301.         echo "obase=64 ; ibase=16 ; $1" | bc
  2302.     fi
  2303. }
  2304.  
  2305.  
  2306.  
  2307. function hex2b32() {
  2308.     if [[ $1 ]]; then
  2309.         echo "obase=32 ; ibase=16 ; $1" | bc
  2310.     fi
  2311. }
  2312.  
  2313.  
  2314.  
  2315. function hex2dec() {
  2316.     if [[ $1 ]]; then
  2317.          echo $((16#$1))
  2318.     fi
  2319. }
  2320.  
  2321.  
  2322.  
  2323. function hex2oct() {
  2324.     if [[ $1 ]]; then
  2325.         echo "obase=8 ; ibase=16 ; $1" | bc
  2326.     fi
  2327. }
  2328.  
  2329.  
  2330.  
  2331. ###### length
  2332. function length()
  2333. {
  2334.     if [ $# -lt 1 ]; then
  2335.         echo "count # of chars in arugment"
  2336.         echo "usage: length [string]"
  2337.     else
  2338.         echo -n $@ | wc -c
  2339.     fi
  2340. }
  2341.  
  2342.  
  2343.  
  2344. ###### finding logs for numbers
  2345. function math-log()
  2346. {
  2347. echo "Enter value: "
  2348. read x
  2349. echo "Natural Log: ln($x) :"
  2350. echo "l($x)" | bc -l
  2351. echo "Ten Base Log: log($x) :"
  2352. echo "l($x)/l(10)" | bc -l
  2353. }
  2354.  
  2355.  
  2356.  
  2357. ###### magic square generator (odd-order squares only!)
  2358. function msquare()
  2359. {
  2360. # Author: mendel cooper
  2361. EVEN=2
  2362. MAXSIZE=31   # 31 rows x 31 cols.
  2363. E_usage=90   # Invocation error.
  2364. dimension=
  2365. declare -i square
  2366. function usage_message()
  2367. {
  2368.   echo "Usage: $0 square-size"
  2369.   echo "   ... where \"square-size\" is an ODD integer"
  2370.   echo "       in the range 3 - 31."  #  Works for squares up to order 159
  2371. }
  2372. function calculate()       # Here's where the actual work gets done.
  2373. {
  2374.   local row col index dimadj j k cell_val=1
  2375.   dimension=$1
  2376.   let "dimadj = $dimension * 3"; let "dimadj /= 2"   # x 1.5, then truncate.
  2377.   for ((j=0; j < dimension; j++))
  2378.   do
  2379.     for ((k=0; k < dimension; k++))
  2380.     do  # Calculate indices, then convert to 1-dim. array index.
  2381.         # Bash doesn't support multidimensional arrays. Pity.
  2382.       let "col = $k - $j + $dimadj"; let "col %= $dimension"
  2383.       let "row = $j * 2 - $k + $dimension"; let "row %= $dimension"
  2384.       let "index = $row*($dimension) + $col"
  2385.       square[$index]=cell_val; ((cell_val++))
  2386.     done
  2387.   done
  2388. }     # Plain math, no visualization required.
  2389. function print_square()               # Output square, one row at a time.
  2390. {
  2391.   local row col idx d1
  2392.   let "d1 = $dimension - 1"   # Adjust for zero-indexed array.
  2393.   for row in $(seq 0 $d1)
  2394.   do
  2395.     for col in $(seq 0 $d1)
  2396.     do
  2397.       let "idx = $row * $dimension + $col"
  2398.       printf "%3d " "${square[idx]}"; echo -n "  "
  2399.     done   # Displays up to 13-order neatly in 80-column term window.
  2400.     echo   # Newline after each row.
  2401.   done
  2402. }
  2403. if [[ -z "$1" ]] || [[ "$1" -gt $MAXSIZE ]]
  2404. then
  2405.   usage_message
  2406. fi
  2407. let "test_even = $1 % $EVEN"
  2408. if [ $test_even -eq 0 ]
  2409. then           # Can't handle even-order squares.
  2410.   usage_message
  2411. fi
  2412. calculate $1
  2413. print_square   # echo "${square[@]}"   # DEBUG
  2414. }
  2415.  
  2416.  
  2417.  
  2418. ###### given a number, show it with comma separated values
  2419. function nicenumber()
  2420. {
  2421. # expects DD and TD to be instantiated. instantiates nicenum
  2422. # or, if a second arg is specified, the output is echoed to stdout
  2423. function nice_number()
  2424. {
  2425.   # Note that we use the '.' as the decimal separator for parsing
  2426.   # the INPUT value to this script. The output value is as specified
  2427.   # by the user with the -d flag, if different from a '.'
  2428.   integer=$(echo $1 | cut -d. -f1)      # left of the decimal
  2429.   decimal=$(echo $1 | cut -d. -f2)      # right of the decimal
  2430.   if [ $decimal != $1 ]; then
  2431.     # there's a fractional part, let's include it.
  2432.     result="${DD:="."}$decimal"
  2433.   fi
  2434.   thousands=$integer
  2435.   while [ $thousands -gt 999 ]; do
  2436.     remainder=$(($thousands % 1000))    # three least significant digits
  2437.     while [ ${#remainder} -lt 3 ] ; do  # force leading zeroes as needed
  2438.       remainder="0$remainder"
  2439.     done
  2440.     thousands=$(($thousands / 1000))    # to left of remainder, if any
  2441.     result="${TD:=","}${remainder}${result}"    # builds right-to-left
  2442.   done
  2443.   nicenum="${thousands}${result}"
  2444.   if [ ! -z $2 ] ; then
  2445.     echo $nicenum
  2446.   fi
  2447. }
  2448. DD="."  # decimal point delimiter, between integer & fractional value
  2449. TD=","  # thousands delimiter, separates every three digits
  2450. while getopts "d:t:" opt; do
  2451.   case $opt in
  2452.     d ) DD="$OPTARG"    ;;
  2453.     t ) TD="$OPTARG"    ;;
  2454.   esac
  2455. done
  2456. shift $(($OPTIND - 1))
  2457. if [ $# -eq 0 ] ; then
  2458.   cat << "EOF" >&2
  2459. Usage: $(basename $0) [-d c] [-t c] numeric value
  2460.        -d specifies the decimal point delimiter (default '.')
  2461.        -t specifies the thousands delimiter (default ',')
  2462. EOF
  2463. fi
  2464. nice_number $1 1    # second arg forces this to 'echo' output
  2465. }
  2466.  
  2467.  
  2468.  
  2469. ###### convert normal to unix
  2470. function normal2unix()
  2471. {
  2472.     echo "${@}" | awk '{print mktime($0)}';
  2473. }
  2474.  
  2475.  
  2476.  
  2477. ###### convert unix to normal
  2478. function unix2normal()
  2479. {
  2480.     echo $1 | awk '{print strftime("%Y-%m-%d %H:%M:%S",$1)}';
  2481. }
  2482.  
  2483.  
  2484.  
  2485. ###### list of numbers with equal width
  2486. function nseq()
  2487. {
  2488. seq -w 0 "$1"
  2489. }
  2490.  
  2491.  
  2492.  
  2493. ###### convert octals
  2494. # copyright 2007 - 2010 Christopher Bratusek
  2495. function oct2all() {
  2496.     if [[ $1 ]]; then
  2497.         echo "octal $1 = binary $(oct2bin $1)"
  2498.         echo "octal $1 = decimal $(oct2dec $1)"
  2499.         echo "octal $1 = hexadecimal $(oct2hex $1)"
  2500.         echo "octal $1 = base32 $(oct2b32 $1)"
  2501.         echo "octal $1 = base64 $(oct2b64 $1)"
  2502.         echo "octal $1 = ascii $(oct2asc $1)"
  2503.     fi
  2504. }
  2505.  
  2506.  
  2507.  
  2508. function oct2asc() {
  2509.     if [[ $1 ]]; then
  2510.         echo -e "\0$(printf %o $((8#$1)))"
  2511.     fi
  2512. }
  2513.  
  2514.  
  2515.  
  2516. function oct2bin() {
  2517.     if [[ $1 ]]; then
  2518.         echo "obase=2 ; ibase=8 ; $1" | bc
  2519.     fi
  2520. }
  2521.  
  2522.  
  2523.  
  2524. function oct2b64() {
  2525.     if [[ $1 ]]; then
  2526.         echo "obase=64 ; ibase=8 ; $1" | bc
  2527.     fi
  2528. }
  2529.  
  2530.  
  2531.  
  2532. function oct2b32() {
  2533.     if [[ $1 ]]; then
  2534.         echo "obase=32 ; ibase=8 ; $1" | bc
  2535.     fi
  2536. }
  2537.  
  2538.  
  2539.  
  2540. function oct2dec() {
  2541.     if [[ $1 ]]; then
  2542.         echo $((8#$1))
  2543.     fi
  2544. }
  2545.  
  2546.  
  2547.  
  2548. function oct2hex() {
  2549.     if [[ $1 ]]; then
  2550.         echo "obase=16 ; ibase=8 ; $1" | bc
  2551.     fi
  2552. }
  2553.  
  2554.  
  2555.  
  2556. ###### convert phone numbers to letters/potentially english words
  2557. # Creator:  asmoore82
  2558. function phone2text()
  2559. {
  2560. echo -n "Enter number: "
  2561. read num
  2562. # Create a list of possibilites for expansion by the shell
  2563. # the "\}" is an ugly hack to get "}" into the replacment string -
  2564. # this is not a clean escape sequence - the litteral "\" is left behind!
  2565. num="${num//2/{a,b,c\}}"
  2566. num="${num//3/{d,e,f\}}"
  2567. num="${num//4/{g,h,i\}}"
  2568. num="${num//5/{j,k,l\}}"
  2569. num="${num//6/{m,n,o\}}"
  2570. num="${num//7/{p,q,r,s\}}"
  2571. num="${num//8/{t,u,v\}}"
  2572. num="${num//9/{w,x,y,z\}}"
  2573. # cleaup from the hack - remove all litteral \'s
  2574. num="${num//\\/}"
  2575. echo ""
  2576. echo "Possible words are:"
  2577. for word in $( eval echo "$num" )
  2578. do
  2579.     echo '>' "$word"
  2580. done
  2581. # End of File
  2582. }
  2583.  
  2584.  
  2585.  
  2586. ###### powers of numerals
  2587. # copyright 2007 - 2010 Christopher Bratusek
  2588. function power() {
  2589.     if [[ $1 ]]; then
  2590.         if [[ $2 ]]; then
  2591.             echo "$1 ^ $2" | bc
  2592.         else    echo "$1 ^ 2" | bc
  2593.         fi
  2594.     fi
  2595. }
  2596.  
  2597.  
  2598.  
  2599. ###### generate prime numbers, without using arrays.
  2600. # script contributed by Stephane Chazelas.
  2601. function primes()
  2602. {
  2603. LIMIT=1000                    # Primes, 2 ... 1000.
  2604. Primes()
  2605. {
  2606.  (( n = $1 + 1 ))             # Bump to next integer.
  2607.  shift                        # Next parameter in list.
  2608. #  echo "_n=$n i=$i_"
  2609.  if (( n == LIMIT ))
  2610.  then echo $*
  2611.  return
  2612.  fi
  2613.  for i; do                    # "i" set to "@", previous values of $n.
  2614. #   echo "-n=$n i=$i-"
  2615.    (( i * i > n )) && break   # Optimization.
  2616.    (( n % i )) && continue    # Sift out non-primes using modulo operator.
  2617.    Primes $n $@               # Recursion inside loop.
  2618.    return
  2619.    done
  2620.    Primes $n $@ $n            #  Recursion outside loop.
  2621.                               #  Successively accumulate
  2622.                   #+ positional parameters.
  2623.                               #  "$@" is the accumulating list of primes.
  2624. }
  2625. Primes 1
  2626. }
  2627.  
  2628.  
  2629.  
  2630. ###### radicals of numbers
  2631. # copyright 2007 - 2010 Christopher Bratusek
  2632. function radical() {
  2633.     if [[ $1 ]]; then
  2634.         echo "sqrt($1)" | bc -l
  2635.     fi
  2636. }
  2637.  
  2638.  
  2639.  
  2640. ###### convert to roman numerals
  2641. function roman-numeral()
  2642. {
  2643. python -c 'while True: print (lambda y,x=[],nums={ 1000:"M",900:"CM",500:"D",400:"CD",100:"C",90:"XC",
  2644. 50:"L",40:"XL",10:"X",9:"IX",5:"V",4:"IV",1:"I"}: (lambda ro=(lambda : map(lambda g,r=lambda b:x.append(
  2645. y[-1]/b),t=lambda v:y.append(y[-1]%v):map(eval,["r(g)","t(g)"]),sorted(nums.keys())[::-1]))():"".join(
  2646. map(lambda fg: map(lambda ht: nums[ht],sorted(nums.keys())[::-1])[fg] * x[fg],range(len(x)))))())([int(
  2647. raw_input("Please enter a number between 1 and 4000: "))])'
  2648. }
  2649.  
  2650.  
  2651.  
  2652. ###### round numerals to whole numbers
  2653. # copyright 2007 - 2010 Christopher Bratusek
  2654. function round() {
  2655.     if [[ $1 ]]; then
  2656.         if [[ $2 ]]; then
  2657.             echo "$(printf %.${2}f $1)"
  2658.         else    echo "$(printf %.0f $1)"
  2659.         fi
  2660.     fi
  2661. }
  2662.  
  2663.  
  2664.  
  2665. ###### ruler that stretches across the terminal
  2666. function ruler() { for s in '....^....|' '1234567890'; do w=${#s}; str=$( for (( i=1; $i<=$(( ($COLUMNS + $w) / $w )) ; i=$i+1 )); do echo -n $s; done ); str=$(echo $str | cut -c -$COLUMNS) ; echo $str; done; }
  2667.  
  2668.  
  2669.  
  2670. ###### convert seconds to minutes, hours, days, and etc.
  2671. # inputs a number of seconds, outputs a string like "2 minutes, 1 second"
  2672. # $1: number of seconds
  2673. function sec2all()
  2674. {
  2675.     local millennia=$((0))
  2676.     local centuries=$((0))
  2677.     local years=$((0))
  2678.     local days=$((0))
  2679.     local hour=$((0))
  2680.     local mins=$((0))
  2681.     local secs=$1
  2682.     local text=""
  2683.     # convert seconds to days, hours, etc
  2684.     millennia=$((secs / 31536000000))
  2685.     secs=$((secs % 31536000000))
  2686.     centuries=$((secs / 3153600000))
  2687.     secs=$((secs % 3153600000))
  2688.     years=$((secs / 31536000))
  2689.     secs=$((secs % 31536000))
  2690.     days=$((secs / 86400))
  2691.     secs=$((secs % 86400))
  2692.     hour=$((secs / 3600))
  2693.     secs=$((secs % 3600))
  2694.     mins=$((secs / 60))
  2695.     secs=$((secs % 60))
  2696.     # build full string from unit strings
  2697.     text="$text$(seconds-convert-part $millennia "millennia")"
  2698.     text="$text$(seconds-convert-part $centuries "century")"
  2699.     text="$text$(seconds-convert-part $years "year")"
  2700.     text="$text$(seconds-convert-part $days "day")"
  2701.     text="$text$(seconds-convert-part $hour "hour")"
  2702.     text="$text$(seconds-convert-part $mins "minute")"
  2703.     text="$text$(seconds-convert-part $secs "second")"
  2704.     # trim leading and trailing whitespace
  2705.     text=${text## }
  2706.     text=${text%% }
  2707.     # special case for zero seconds
  2708.     if [ "$text" == "" ]; then
  2709.         text="0 seconds"
  2710.     fi
  2711.     # echo output for the caller
  2712.     echo ${text}
  2713. }
  2714. # formats a time unit into a string
  2715. # $1: integer count of units: 0, 6, etc
  2716. # $2: unit name: "hour", "minute", etc
  2717. function seconds-convert-part()
  2718. {
  2719.     local unit=$1
  2720.     local name=$2
  2721.     if [ $unit -ge 2 ]; then
  2722.         echo " ${unit} ${name}s"
  2723.     elif [ $unit -ge 1 ]; then
  2724.         echo " ${unit} ${name}"
  2725.     else
  2726.         echo ""
  2727.     fi
  2728. }
  2729.  
  2730.  
  2731.  
  2732. ###### finding the square root of numbers
  2733. function sqrt()
  2734. {
  2735. echo "sqrt ("$1")" | bc -l
  2736. }
  2737.  
  2738.  
  2739.  
  2740. ###### trigonmetry calculations with angles
  2741. function trig-angle()
  2742. {
  2743. echo "Enter angle in degree: "
  2744. read deg
  2745. # Note: Pi calculation
  2746. # tan(pi/4) = 1
  2747. # atan(1) = pi/4 and
  2748. # pi = 4*atan(1)
  2749. pi=`echo "4*a(1)" | bc -l`
  2750. rad=`echo "$deg*($pi/180)" | bc -l`
  2751. echo "$deg Degree = $rad Radian"
  2752. echo "Sin($deg): "
  2753. echo "s($rad)" | bc -l
  2754. echo "Cos($deg): "
  2755. echo "c($rad)" | bc -l
  2756. echo "Tan($deg): "
  2757. echo "s($rad)/c($rad)" | bc -l
  2758. }
  2759.  
  2760.  
  2761.  
  2762. ##################################################
  2763. # Ask                        #
  2764. ##################################################
  2765.  
  2766. function ask()
  2767. {
  2768.     echo -n "$@" '[y/n] ' ; read ans
  2769.     case "$ans" in
  2770.         y*|Y*) return 0 ;;
  2771.         *) return 1 ;;
  2772.     esac
  2773. }
  2774.  
  2775.  
  2776.  
  2777. ##################################################
  2778. # Escape potential tarbombs          #
  2779. ##################################################
  2780.  
  2781. function atb() { l=$(tar tf $1); if [ $(echo "$l" | wc -l) -eq $(echo "$l" | grep $(echo "$l" | head -n1) | wc -l) ]; then tar xf $1; else mkdir ${1%.tar.gz} && tar xf $1 -C ${1%.tar.gz}; fi ; }
  2782.  
  2783.  
  2784.  
  2785. ##################################################
  2786. # Get the headlines of an atom feed      #
  2787. ##################################################
  2788.  
  2789. function atomtitles()
  2790. {
  2791. curl --silent $1 | xmlstarlet sel -N atom="http://www.w3.org/2005/Atom" -t -m /atom:feed/atom:entry -v atom:title -n
  2792. }
  2793.  
  2794.  
  2795.  
  2796. ##################################################
  2797. # Rip audio from video               #
  2798. ##################################################
  2799.  
  2800. ###### ("$1" for output file & "$2" for input file)
  2801. function audioextract()
  2802. {
  2803. mplayer -ao pcm -vo null -vc dummy -dumpaudio -dumpfile "$1" "$2"
  2804. }
  2805.  
  2806.  
  2807.  
  2808. ###### extract audio from DVD VOB files
  2809. # USAGE:    audioextractdvd input_file.vob output_file.ac3
  2810. function audioextract_dvd()
  2811. {
  2812. mplayer "$1" -aid 128 -dumpaudio -dumpfile "$2"
  2813. }
  2814.  
  2815.  
  2816.  
  2817. ##################################################
  2818. # Download AUR package using best guess at   #
  2819. # filename                   #
  2820. ##################################################
  2821.  
  2822. function aurget() {
  2823.   local DIR=$HOME/Packages
  2824.   cd $DIR && wget http://aur.archlinux.org/packages/${1}/${1}.tar.gz
  2825.   ls -l
  2826. }
  2827.  
  2828.  
  2829.  
  2830. ##################################################
  2831. # ~/ functions                   #
  2832. ##################################################
  2833.  
  2834. function backupsfolder()
  2835. {
  2836.     if [ -d $HOME/backups_html ]; then
  2837.         chown -R $USER:www-data $HOME/backups_html
  2838.         chmod 755 $HOME/backups_html
  2839.         find $HOME/backups_html/ -type d -exec chmod 775 {} \;
  2840.         find $HOME/backups_html/ -type f -exec chmod 664 {} \;
  2841.         chmod 755 $HOME
  2842.     fi
  2843. }
  2844.  
  2845.  
  2846.  
  2847. function private()
  2848. {
  2849.     find $HOME -type d -exec chmod 700 {} \;
  2850.     find $HOME -type f -exec chmod 600 {} \;
  2851.     find $HOME/bin -type f -exec chmod +x {} \;
  2852.     find $HOME/.dropbox-dist/dropbox* -type f -exec chmod +x {} \;
  2853. }
  2854.  
  2855.  
  2856.  
  2857. function publicfolder()
  2858. {
  2859.     if [ -d $HOME/public_html ]; then
  2860.         chown -R $USER:www-data $HOME/public_html
  2861.         chmod 755 $HOME/public_html
  2862.         find $HOME/public_html/ -type d -exec chmod 775 {} \;
  2863.         find $HOME/public_html/ -type f -exec chmod 664 {} \;
  2864.         chmod 755 $HOME
  2865.     fi
  2866. }
  2867.  
  2868.  
  2869.  
  2870. function setperms()
  2871. {
  2872.     echo "setting proper permissions in ~/"
  2873.     private
  2874.     public
  2875. }
  2876.  
  2877.  
  2878.  
  2879. function wwwrc()
  2880. {
  2881.     alias mv="mv"
  2882.     mv -f ~/.[a-z]*.html ~/public_html/
  2883.     chmod 644 ~/public_html/.[a-z]*.html
  2884.     chown $USER:www-data ~/public_html/.[a-z]*.html
  2885.     alias mv="mv -i"
  2886. }
  2887.  
  2888.  
  2889.  
  2890. ##################################################
  2891. # Backup .bash* files                #
  2892. ##################################################
  2893.  
  2894. function backup_bashfiles()
  2895. {
  2896.   ARCHIVE="$HOME/bash_dotfiles_$(date +%Y%m%d_%H%M%S).tar.gz";
  2897.   cd ~
  2898.   tar -czvf $ARCHIVE .bash_profile .bashrc .bash_functions .bash_aliases .bash_prompt
  2899.   echo "All backed up in $ARCHIVE";
  2900. }
  2901.  
  2902.  
  2903.  
  2904. ##################################################
  2905. # Creates a backup of the file passed as     #
  2906. # parameter with the date and time       #
  2907. ##################################################
  2908.  
  2909. function bak()
  2910. {
  2911.   cp $1 $1_`date +%H:%M:%S_%d-%m-%Y`
  2912. }
  2913.  
  2914.  
  2915.  
  2916. ##################################################
  2917. # Good bash tips for everyone            #
  2918. ##################################################
  2919.  
  2920. function bashtips() {
  2921. # copyright 2007 - 2010 Christopher Bratusek
  2922. cat <<EOF
  2923. DIRECTORIES
  2924. -----------
  2925. ~-          Previous working directory
  2926. pushd tmp   Push tmp && cd tmp
  2927. popd        Pop && cd
  2928. GLOBBING AND OUTPUT SUBSTITUTION
  2929. --------------------------------
  2930. ls a[b-dx]e Globs abe, ace, ade, axe
  2931. ls a{c,bl}e Globs ace, able
  2932. \$(ls)      \`ls\` (but nestable!)
  2933. HISTORY MANIPULATION
  2934. --------------------
  2935. !!        Last command
  2936. !?foo     Last command containing \`foo'
  2937. ^foo^bar^ Last command containing \`foo', but substitute \`bar'
  2938. !!:0      Last command word
  2939. !!:^      Last command's first argument
  2940. !\$       Last command's last argument
  2941. !!:*      Last command's arguments
  2942. !!:x-y    Arguments x to y of last command
  2943. C-s       search forwards in history
  2944. C-r       search backwards in history
  2945. LINE EDITING
  2946. ------------
  2947. M-d     kill to end of word
  2948. C-w     kill to beginning of word
  2949. C-k     kill to end of line
  2950. C-u     kill to beginning of line
  2951. M-r     revert all modifications to current line
  2952. C-]     search forwards in line
  2953. M-C-]   search backwards in line
  2954. C-t     transpose characters
  2955. M-t     transpose words
  2956. M-u     uppercase word
  2957. M-l     lowercase word
  2958. M-c     capitalize word
  2959. COMPLETION
  2960. ----------
  2961. M-/     complete filename
  2962. M-~     complete user name
  2963. M-@     complete host name
  2964. M-\$    complete variable name
  2965. M-!     complete command name
  2966. M-^     complete history
  2967. EOF
  2968. }
  2969.  
  2970.  
  2971.  
  2972. ##################################################
  2973. # Execute a given Linux command on a group of    #
  2974. # files                      #
  2975. ##################################################
  2976.  
  2977. ###### Example: batchexec sh ls     # lists all files that have the extension 'sh'
  2978. # Example: batchexec sh chmod 755   # 'chmod 755' all files that have the extension 'sh'
  2979. function batchexec()
  2980. {
  2981. find . -type f -iname '*.'${1}'' -exec ${@:2}  {} \; ;
  2982. }
  2983.  
  2984.  
  2985.  
  2986. ##################################################
  2987. # Clock - A bash clock that can run in your  #
  2988. # terminal window.               #
  2989. ##################################################
  2990.  
  2991. ###### binary clock
  2992. function bclock()
  2993. {
  2994. watch -n 1 'echo "obase=2;`date +%s`" | bc'
  2995. }
  2996.  
  2997.  
  2998.  
  2999. ###### binary clock
  3000. function bclock2()
  3001. {
  3002. perl -e 'for(;;){@d=split("",`date +%H%M%S`);print"\r";for(0..5){printf"%.4b ",$d[$_]}sleep 1}'
  3003. }
  3004.  
  3005.  
  3006.  
  3007. function clock()
  3008. {
  3009. while true;do clear;echo "===========";date +"%r";echo "===========";sleep 1;done
  3010. }
  3011.  
  3012.  
  3013.  
  3014. ##################################################
  3015. # Appends a '&' to a command so it will run in   #
  3016. # the background                 #
  3017. ##################################################
  3018.  
  3019. ###### useful for aliases
  3020. function bg_wrapper()
  3021. {
  3022.     "$@" &
  3023. }
  3024.  
  3025.  
  3026.  
  3027. ##################################################
  3028. # Substitutes underscores for blanks in all the  #
  3029. # filenames in a directory           #
  3030. ##################################################
  3031.  
  3032. function blank_rename()
  3033. {
  3034. ONE=1                     # For getting singular/plural right (see below).
  3035. number=0                  # Keeps track of how many files actually renamed.
  3036. FOUND=0                   # Successful return value.
  3037. for filename in *         #Traverse all files in directory.
  3038. do
  3039.      echo "$filename" | grep -q " "         #  Check whether filename
  3040.      if [ $? -eq $FOUND ]                   #+ contains space(s).
  3041.      then
  3042.        fname=$filename                      # Yes, this filename needs work.
  3043.        n=`echo $fname | sed -e "s/ /_/g"`   # Substitute underscore for blank.
  3044.        mv "$fname" "$n"                     # Do the actual renaming.
  3045.        let "number += 1"
  3046.      fi
  3047. done
  3048. if [ "$number" -eq "$ONE" ]                 # For correct grammar.
  3049. then
  3050.  echo "$number file renamed."
  3051. else
  3052.  echo "$number files renamed."
  3053. fi
  3054. }
  3055.  
  3056.  
  3057.  
  3058. ##################################################
  3059. # Bookmarking                    #
  3060. ##################################################
  3061.  
  3062. ###### bookmarking the current directory in 'alias' form
  3063. function bookmark() {
  3064.     # copyright 2007 - 2010 Christopher Bratusek
  3065.     if [[ $1 != "" && $(alias | grep -w go-$1) == "" ]]; then
  3066.         echo "alias go-$1='cd $PWD'" >> $HOME/.bookmarks
  3067.         . $HOME/.bookmarks
  3068.     elif [[ $1 == "" ]]; then
  3069.         echo "need name for the bookmark."
  3070.     else    echo "bookmark go-$1 already exists."
  3071.     fi
  3072. }
  3073.  
  3074.  
  3075.  
  3076. function unmark() {
  3077.     # copyright 2007 - 2010 Christopher Bratusek
  3078.     if [[ $(alias | grep -w go-$1= ) != "" ]]; then
  3079.         sed -e "/go-$1/d" -i $HOME/.bookmarks
  3080.         xunalias go-$1
  3081.     fi
  3082. }
  3083.  
  3084.  
  3085.  
  3086. ###### copies/moves files to a bookmarked dir
  3087. # cto file1.jpg file2.jpg file3.jpg pics
  3088. function cto() {
  3089.     eval lastarg=\${$#}
  3090.     targetdir=`getBookmark $lastarg`
  3091.     echo "Copying files to $targetdir"
  3092.     if [ -n "$targetdir" ]; then
  3093.         for dir in "$@";
  3094.             do
  3095.                 if [ "$dir" != $lastarg ]; then
  3096.                     cp -iv "$dir" "$targetdir"
  3097.                 fi
  3098.             done
  3099.     fi
  3100. }
  3101.  
  3102.  
  3103.  
  3104. # mto vid1.avi vid2.avi videos
  3105. function mto() {
  3106.     eval lastarg=\${$#}
  3107.     targetdir=`getBookmark $lastarg`
  3108.     echo "Moving files to $targetdir"
  3109.     if [ -n "$targetdir" ]; then
  3110.         for dir in "$@";
  3111.             do
  3112.                 if [ "$dir" != $lastarg ]; then
  3113.                     mv -iv "$dir" "$targetdir"
  3114.                 fi
  3115.             done
  3116.     fi
  3117. }
  3118.  
  3119.  
  3120.  
  3121. ###### Directory Bookmarks for BASH (c) 2009, Ira Chayut, Version 090927
  3122. # DirB and its implementation in this file are the product of, and
  3123. # copyrighted by Ira Chayut.  You are granted a non-exclusive, royalty-free
  3124. # license to use, reproduce, modify and create derivative works from DirB;
  3125. # providing that credit is given to DirB as a source material.
  3126. # The lastest version is available from: http://www.dirb.info/bashDirB.  Ira can
  3127. # be reached at ira@dirb.info.
  3128. # By default DirB will have the shell echo the current working directory out
  3129. # to the title bars of Xterm windows.  To disable this behavior, comment
  3130. # out the next line.
  3131. # PS1="\[\033]0;\w\007\]\t \!> "
  3132. # If the repository of bookmarks does not exist, create it
  3133. if  [ ! -e ~/.DirB ]
  3134. then
  3135.     mkdir ~/.DirB
  3136. fi
  3137.  
  3138.  
  3139.  
  3140. ###### "d" - Display (or Dereference) a saved bookmark
  3141. # to use: cd "$(d xxx)"
  3142. function d() {
  3143.     # if the bookmark exists, then extract its directory path and print it
  3144.     if [ -e ~/.DirB/"$1" ]
  3145.     then
  3146.         sed -e 's/\$CD //' -e 's/\\//g' ~/.DirB/"$1"
  3147.  
  3148.     # if the bookmark does not exists, complain and exit with a failing code
  3149.     else
  3150.         echo bash: DirB: ~/.DirB/"$1" does not exist >&2
  3151.         false
  3152.     fi
  3153. }
  3154.  
  3155.  
  3156.  
  3157. ###### "g" - Go to bookmark
  3158. function g() {
  3159.     # if no arguments, then just go to the home directory
  3160.     if [ -z "$1" ]
  3161.     then
  3162.         cd
  3163.     else
  3164.         # if $1 is in ~/.DirB and does not begin with ".", then go to it
  3165.         if [ -f ~/.DirB/"$1" -a ${1:0:1} != "." ]
  3166.         then
  3167.             # update the bookmark's timestamp and then execute it
  3168.             touch ~/.DirB/"$1" ;
  3169.             CD=cd source ~/.DirB/"$1" ;
  3170.         # else just do a "cd" to the argument, usually a directory path of "-"
  3171.         else
  3172.             cd "$1"
  3173.         fi
  3174.     fi
  3175. }
  3176.  
  3177.  
  3178.  
  3179. ###### "p" - Push a bookmark
  3180. function p() {
  3181.     # Note, the author's preference is to list the directory stack in a single
  3182.     # column.  Thus, the standard behavior of "pushd" and "popd" have been
  3183.     # replaced by discarding the normal output of these commands and using a
  3184.     # "dirs -p" after each one.
  3185.  
  3186.     # if no argument given, then just pushd and print out the directory stack
  3187.     if [ -z "$1" ]
  3188.     then
  3189.         pushd > /dev/null && dirs -p
  3190.  
  3191.     # if $1 is a dash, then just do a "popd" and print out the directory stack
  3192.     elif [ "$1" == "-" ]
  3193.     then
  3194.         popd > /dev/null
  3195.         dirs -p
  3196.     else
  3197.         # if $1 is in ~/.DirB and does not begin with ".", then go to it
  3198.         # and then print out the directory stack
  3199.         if [ -f ~/.DirB/"$1" -a "${1:0:1}" != "." ]
  3200.             then
  3201.                 touch ~/.DirB/$1 ;
  3202.                 CD=pushd source ~/.DirB/$1 > /dev/null && dirs -p ;
  3203.  
  3204.         # else just do a "pushd" and print out the directory stack
  3205.         else
  3206.             pushd "$1" > /dev/null && dirs -p
  3207.         fi
  3208.     fi
  3209. }
  3210.  
  3211.  
  3212.  
  3213. ###### "r" - Remove a saved bookmark
  3214. function r() {
  3215.     # if the bookmark file exists, remove it
  3216.     if [ -e ~/.DirB/"$1" ]
  3217.     then
  3218.         rm ~/.DirB/"$1"
  3219.  
  3220.     # if the bookmark file does not exist, complain and exit with a failing code
  3221.     else
  3222.         echo bash: DirB: ~/.DirB/"$1" does not exist >&2
  3223.         false
  3224.     fi
  3225. }
  3226.  
  3227.  
  3228.  
  3229. ###### "s" - Save bookmark
  3230. function s() {
  3231.     if [ -n "$2" ]
  3232.     then
  3233.         # build the bookmark file with the contents "$CD directory_path"
  3234.         ( echo '$CD ' \"$2\" > ~/.DirB/"$1" ;) > /dev/null 2>&1
  3235.     else
  3236.         # build the bookmark file with the contents "$CD directory_path"
  3237.         ( echo -n '$CD ' > ~/.DirB/"$1" ;
  3238.           pwd | sed "s/ /\\\\ /g" >> ~/.DirB/"$1" ; ) > /dev/null 2>&1
  3239.     fi
  3240.     # if the bookmark could not be created, print an error message and
  3241.     # exit with a failing return code
  3242.     if [ $? != 0 ]
  3243.     then
  3244.         echo bash: DirB: ~/.DirB/"$1" could not be created >&2
  3245.         false
  3246.     fi
  3247. }
  3248.  
  3249.  
  3250.  
  3251. ###### "sl" - Saved bookmark Listing
  3252. function sl() {
  3253.     # if the "-l" argument is given, then do a long listing, passing any
  3254.     # remaining arguments to "ls", printing in reverse time order.  Pass the
  3255.     # output to "less" to page the output if longer than a screen in length.
  3256.     if [ "$1" == "-l" ]
  3257.     then
  3258.         shift
  3259.         ( cd ~/.DirB ;
  3260.         ls -lt $* |
  3261.             sed -e 's/  */ /g' -e '/^total/d' \
  3262.                 -e 's/^\(... \)\([0-9] \)/\1 \2/' |
  3263.             cut -d ' ' -s -f6- | sed -e '/ [0-9] /s// &/' | less -FX ; )
  3264.  
  3265.     # else print the short form of the bookmarks in reverse time order
  3266.     else
  3267.         ( cd ~/.DirB ; ls -xt $* ; )
  3268.     fi
  3269. }
  3270.  
  3271.  
  3272.  
  3273. ###### simple bookmark system
  3274. function getBookmark() {
  3275.     case "$1" in
  3276.     video|vids|vid) echo "~/Videos" ;; # video, vids and vid are shortcuts to use with the functions below, the bookmarked directory is "~/videos"
  3277.     images|img|pics|pictures) echo "~/Pictures";;
  3278.     *) echo "" ;;
  3279.     esac
  3280. }
  3281.  
  3282.  
  3283.  
  3284. ###### list contents of a bookmarked dir without
  3285. # going there: list vids
  3286. function list() {
  3287.     dir=`getBookmark $1`
  3288.     echo $dir
  3289.     if [ -n "$dir" ]; then
  3290.         ls "$dir"
  3291.     fi
  3292. }
  3293.  
  3294.  
  3295.  
  3296. ###### same as "list" but with details: llist vids
  3297. function llist() {
  3298.     dir=`getBookmark $1`
  3299.     echo $dir
  3300.     if [ -n "$dir" ]; then
  3301.         ll "$dir"
  3302.     fi
  3303. }
  3304.  
  3305.  
  3306.  
  3307. ##################################################
  3308. # Create box of '#' characters around given      #
  3309. # string                     #
  3310. ##################################################
  3311.  
  3312. function box() { t="$1xxxx";c=${2:-#}; echo ${t//?/$c}; echo "$c $1 $c"; echo ${t//?/$c}; }
  3313.  
  3314.  
  3315.  
  3316. ##################################################
  3317. # Download all videos in your Boxee queue    #
  3318. ##################################################
  3319.  
  3320. # Gets all videos in your boxee queue with a URL associated with them and attempts to download each using get_flash_videos
  3321. function boxeedl()
  3322. {
  3323. for i in $(curl -u <username> http://app.boxee.tv/api/get_queue | xml2 | grep /boxeefeed/message/object/url | cut -d "=" -f 2,3); do get_flash_videos $i; done
  3324. }
  3325.  
  3326.  
  3327.  
  3328. ##################################################
  3329. # Randomness                     #
  3330. ##################################################
  3331.  
  3332. ###### This script models Brownian motion:
  3333. # random wanderings of tiny particles in fluid, as they are buffeted
  3334. # by random currents and collisions (colloquially known as "Drunkard's Walk")
  3335. # Author: Mendel Cooper
  3336. function brownian()
  3337. {
  3338. PASSES=500                  #  Number of particle interactions / marbles.
  3339. ROWS=10                     #  Number of "collisions" (or horiz. peg rows).
  3340. RANGE=3                     #  0 - 2 output range from $RANDOM.
  3341. POS=0                       #  Left/right position.
  3342. RANDOM=$$                   #  Seeds the random number generator from PID of script.
  3343. declare -a Slots            # Array holding cumulative results of passes.
  3344. NUMSLOTS=21                 # Number of slots at bottom of board.
  3345. function Initialize_Slots() {   # Zero out all elements of the array.
  3346. for i in $( seq $NUMSLOTS )
  3347. do
  3348.   Slots[$i]=0
  3349. done
  3350. echo                        # Blank line at beginning of run.
  3351.   }
  3352. function Show_Slots() {
  3353. echo -n " "
  3354. for i in $( seq $NUMSLOTS )     # Pretty-print array elements.
  3355. do
  3356.   printf "%3d" ${Slots[$i]}     # Allot three spaces per result.
  3357. done
  3358. echo                # Row of slots:
  3359. echo " |__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|__|"
  3360. echo "                                ^^"
  3361. echo                #  Note that if the count within any particular slot exceeds 99,
  3362.                     #+ it messes up the display.
  3363.                     #  Running only(!) 500 passes usually avoids this.
  3364.   }
  3365. function Move() {               # Move one unit right / left, or stay put.
  3366.   Move=$RANDOM              # How random is $RANDOM? Well, let's see ...
  3367.   let "Move %= RANGE"       # Normalize into range of 0 - 2.
  3368.   case "$Move" in
  3369.     0 ) ;;                  # Do nothing, i.e., stay in place.
  3370.     1 ) ((POS--));;         # Left.
  3371.     2 ) ((POS++));;         # Right.
  3372.     * ) echo -n "Error ";;      # Anomaly! (Should never occur.)
  3373.   esac
  3374.   }
  3375. function Play() {               # Single pass (inner loop).
  3376. i=0
  3377. while [ "$i" -lt "$ROWS" ]      # One event per row.
  3378. do
  3379.   Move
  3380.   ((i++));
  3381. done
  3382. SHIFT=11                        # Why 11, and not 10?
  3383. let "POS += $SHIFT"             # Shift "zero position" to center.
  3384. (( Slots[$POS]++ ))             # DEBUG: echo $POS
  3385.   }
  3386. function Run() {                # Outer loop.
  3387. p=0
  3388. while [ "$p" -lt "$PASSES" ]
  3389. do
  3390.   Play
  3391.   (( p++ ))
  3392.   POS=0                         # Reset to zero. Why?
  3393. done
  3394.   }
  3395. # main()
  3396. Initialize_Slots
  3397. Run
  3398. Show_Slots
  3399. }
  3400.  
  3401.  
  3402.  
  3403. ###### flip a single coin 1000 times and show results
  3404. function coin-flip()
  3405. {
  3406. SEED=$"(head -1 /dev/urandom | od -N 1 | awk '{ print $2 }')"
  3407. RANDOM=$SEED
  3408. SIDES=2             # A coin has 2 sides.
  3409. MAXTHROWS=1000      # Increase this if you have nothing better to do with your time.
  3410. throw=0             # Throw count.
  3411. heads=0             # Must initialize counts to zero,
  3412. tails=0             # since an uninitialized variable is null, not zero.
  3413. function print_result()
  3414. {
  3415. echo
  3416. echo "heads =   $heads"
  3417. echo "tails =   $tails"
  3418. echo
  3419. }
  3420. function update_count()
  3421. {
  3422. case "$1" in
  3423.   0) let "heads += 1";; # Since coin has no "zero", this corresponds to 1.
  3424.   1) let "tails += 1";; # And this to 2, etc.
  3425. esac
  3426. }
  3427. echo
  3428. while [ "$throw" -lt "$MAXTHROWS" ]
  3429. do
  3430.   let "coin1 = RANDOM % $SIDES"
  3431.   update_count $coin1
  3432.   let "throw += 1"
  3433. done
  3434. print_result
  3435. echo "Out of a total of "$MAXTHROWS" tosses."
  3436. echo "Change \"MAXTHROWS=1000\" if you want a different number of tosses."
  3437. }
  3438.  
  3439.  
  3440.  
  3441. ###### roll a single die of "$1" sides, just once
  3442. # default number of sides is 6
  3443. # written by Dallas Vogels
  3444. function one-die()
  3445. {
  3446. function roll_die() {
  3447.   # capture parameter
  3448.   declare -i DIE_SIDES=$1
  3449.   # check for die sides
  3450.   if [ ! $DIE_SIDES -gt 0 ]; then
  3451.     # default to 6
  3452.     DIE_SIDES=6
  3453.   fi
  3454.   # echo to screen
  3455.   echo $[ ( $RANDOM % $DIE_SIDES )  + 1 ]
  3456. }
  3457. # roll_die 10  # returns 1 to 10 as per 10 sides
  3458. # roll_die 2   # returns 1 or 2 as per 2 sides
  3459. roll_die "$1"
  3460. }
  3461.  
  3462.  
  3463.  
  3464. ###### select random card from a deck
  3465. function pick-card()
  3466. {
  3467. # This is an example of choosing random elements of an array.
  3468. # Pick a card, any card.
  3469. Suites="Clubs
  3470. Diamonds
  3471. Hearts
  3472. Spades"
  3473. Denominations="2
  3474. 3
  3475. 4
  3476. 5
  3477. 6
  3478. 7
  3479. 8
  3480. 9
  3481. 10
  3482. Jack
  3483. Queen
  3484. King
  3485. Ace"
  3486. # Note variables spread over multiple lines.
  3487. suite=($Suites)                # Read into array variable.
  3488. denomination=($Denominations)
  3489. num_suites=${#suite[*]}        # Count how many elements.
  3490. num_denominations=${#denomination[*]}
  3491. echo -n "${denomination[$((RANDOM%num_denominations))]} of "
  3492. echo ${suite[$((RANDOM%num_suites))]}
  3493. # $bozo sh pick-cards.sh
  3494. # Jack of Clubs
  3495. # Thank you, "jipe," for pointing out this use of $RANDOM.
  3496. }
  3497.  
  3498.  
  3499.  
  3500. ###### random number (out of whatever you input)
  3501. # example:  random 10   =   4
  3502. # copyright 2007 - 2010 Christopher Bratusek
  3503. function random() {
  3504.     if [[ $1 == -l ]]; then
  3505.         echo $(cat /dev/urandom | tr -cd '[:digit:]' | head -c ${2-5})
  3506.     elif [[ $1 == -r ]]; then
  3507.         echo $((RANDOM%${2}))
  3508.     else    echo $((RANDOM%${1}))
  3509.     fi
  3510. }
  3511.  
  3512.  
  3513.  
  3514. ###### create random blank files
  3515. function randomblanks()
  3516. {
  3517. for ((  i = 0 ;  i < $1;  i++  )); do touch $RANDOM; done
  3518. }
  3519.  
  3520.  
  3521.  
  3522. ###### random file
  3523. # copyright 2007 - 2010 Christopher Bratusek
  3524. function randomfile() {
  3525.     case $1 in
  3526.             *first)
  3527.                 sed -n '1p' $HOME/.randomhistory
  3528.             ;;
  3529.             *last)
  3530.                 sed -n '$p' $HOME/.randomhistory
  3531.             ;;
  3532.             *n)
  3533.                 sed -n "${2}p" $HOME/.randomhistory
  3534.             ;;
  3535.             *l)
  3536.                 wc -l $HOME/.randomhistory | gawk '{print $1}'
  3537.             ;;
  3538.             *c)
  3539.                 rm $HOME/.randomhistory
  3540.             ;;
  3541.             *help )
  3542.                 echo -e "\n${ewhite}Usage:\n"
  3543.                 echo -e "${eorange}randomfile${ewhite} | ${egreen}--first ${eiceblue}[get the first file in the history]\
  3544.                 \n${eorange}randomfile${ewhite} | ${egreen}--last ${eiceblue}[get the last file in the history]\
  3545.                 \n${eorange}randomfile${ewhite} | ${egreen}--n ${eiceblue}[get the NUMBERth file in the history]\
  3546.                 \n${eorange}randomfile${ewhite} | ${egreen}--l ${eiceblue}[get the number of files in history]\
  3547.                 \n${eorange}randomfile${ewhite} | ${egreen}--c ${eiceblue}[clear the history]\n" | column -t
  3548.                 tput sgr0
  3549.             ;;
  3550.             *)
  3551.                 if [[ ! "$FILES" ]]; then
  3552.                     files=(*)
  3553.                 else    files=("$FILES")
  3554.                 fi
  3555.                 n=${#files[@]}
  3556.                 RANDOMFILE="${files[RANDOM % n]}"
  3557.                 echo "$RANDOMFILE" >> $HOME/.randomhistory
  3558.                 if [[ ! "$@" ]]; then
  3559.                     echo "$RANDOMFILE"
  3560.                 else    "$@" "$RANDOMFILE"
  3561.                 fi
  3562.             ;;
  3563.     esac
  3564. }
  3565.  
  3566.  
  3567.  
  3568. ###### pulls a random line from text file
  3569. function randomline()
  3570. {
  3571. # AUTHOR: David Ivan Stark (clyphox), clyphox@gmail.com
  3572. if [ "$1" ];then  #checking if we were passed a filename/variable
  3573.         FileName="$1"  #just an easier variable to work with
  3574.         if [ ! -f "$FileName" ];then  #check if it is a file
  3575.             echo "Err: $FileName is not a file"
  3576.         fi
  3577.         #Count how many lines in the file
  3578.         LineCount="$(wc -l "$FileName" | cut -f 1 -d ' ')"
  3579.         #Dont continue if we have less than 1 line
  3580.         if [ "$LineCount" -gt "1" ];then
  3581.                 #Test past.. selecting random line
  3582.                 TargetLine=$[ ( $RANDOM % $LineCount )  + 1 ]
  3583.                 Output="$(sed -n "${TargetLine}p" "$FileName")"
  3584.                 echo "$Output"
  3585.             else
  3586.                 echo need a file with more than 1 line... cmon...
  3587.         fi
  3588.     else    #seems we didnt get any input
  3589.         echo "Please specify a text file"
  3590. fi
  3591. }
  3592.  
  3593.  
  3594.  
  3595. ###### Generates neverending list of random numbers
  3596. function randomnumbers()
  3597. {
  3598. while :
  3599. do
  3600.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3601.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3602.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3603.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3604.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3605.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3606.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3607.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3608.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3609.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3610.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3611.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3612.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3613.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3614.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3615.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3616.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3617.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3618.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3619.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3620.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3621.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3622.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3623.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3624.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3625.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3626.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3627.  echo $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM
  3628. done
  3629. }
  3630.  
  3631.  
  3632.  
  3633. ###### Random wallpaper (add whatever wallpaper directory(s) you wish after 'BACKGROUND_DIRS')
  3634. function randomwp()
  3635. {
  3636. cat > "/tmp/randomwp.py" <<"End-of-message"
  3637. #!/usr/bin/env python
  3638. BACKGROUND_DIRS = ['/usr/share/backgrounds', '~/Pictures/Backgrounds']
  3639. EXTENSIONS = ['jpeg', 'jpg', 'bmp', 'png', 'svg']
  3640. import os, glob, random, itertools, gconf
  3641. files = list(itertools.chain(*[[os.path.join(dirpath, name)
  3642.                                 for name in filenames]
  3643.                                for dirpath, dirnames, filenames in
  3644.                                itertools.chain(*[os.walk(os.path.expanduser(d))
  3645.                                                  for d in BACKGROUND_DIRS])]))
  3646. gconf.client_get_default().set_string(
  3647.     '/desktop/gnome/background/picture_filename',
  3648.     random.choice(files))
  3649. End-of-message
  3650. chmod +x "/tmp/randomwp.py"
  3651. "/tmp/randomwp.py"
  3652. rm "/tmp/randomwp.py"
  3653. }
  3654.  
  3655.  
  3656.  
  3657. ###### automatic wallpaper switcher for Gnome
  3658. # Usage: randomwpt "bash directory_name" "timeout_in_seconds"
  3659. function randomwpt()
  3660. {
  3661. if [ $# -ne 2 ];then
  3662.     echo -n "Usage: $0 directory_name timeout_in_seconds
  3663.     Leave the directory name blank for Current Directory
  3664.     For you lazy pal, I assume timeout as 5 sec and Directory as current
  3665.     Do you want to accept this settings? (Y/n): ";
  3666.     read response
  3667.     if [[ "$response" =~ ^[^yY] ]];then
  3668.         exit 0
  3669.     fi
  3670. fi
  3671. function set_wallpaper() {
  3672.     gconftool-2 -s /desktop/gnome/background/picture_options "centered" -t string;
  3673.     gconftool-2 -s /desktop/gnome/background/picture_filename "$1" -t string;
  3674. }
  3675. TIMEOUT=${2-5};
  3676. WALL_DIR=${1-`pwd`};
  3677. echo "Timeout value is: $TIMEOUT";
  3678. echo "Directory is: $WALL_DIR";
  3679. echo
  3680. if [ ! -d "$WALL_DIR" ];then
  3681.     echo "The Directory Specified is invalid..";
  3682.     exit 1;
  3683. fi
  3684. filelst="$(find "$WALL_DIR" -type f -name '*.jpg' -o -name '*.png')";
  3685. if [ -z "$filelst" ];then
  3686.     echo "No Suitable files found in this location: $WALL_DIR";
  3687.     exit 1;
  3688. fi
  3689. while true;do
  3690.     filename=`echo "$filelst" | shuf -n 1`
  3691.     set_wallpaper "$filename";
  3692.     sleep $TIMEOUT;
  3693. done
  3694. }
  3695.  
  3696.  
  3697.  
  3698. ###### roll a single die 1000 times and show results
  3699. function roll-die()
  3700. {
  3701. SEED=$"(head -1 /dev/urandom | od -N 1 | awk '{ print $2 }')"
  3702. RANDOM=$SEED
  3703. PIPS=6              # A die has 6 pips.
  3704. MAXTHROWS=1000      # Increase this if you have nothing better to do with your time.
  3705. throw=0             # Throw count.
  3706. ones=0              #  Must initialize counts to zero,
  3707. twos=0              #+ since an uninitialized variable is null, not zero.
  3708. threes=0
  3709. fours=0
  3710. fives=0
  3711. sixes=0
  3712. function print_result()
  3713. {
  3714. echo
  3715. echo "ones =   $ones"
  3716. echo "twos =   $twos"
  3717. echo "threes = $threes"
  3718. echo "fours =  $fours"
  3719. echo "fives =  $fives"
  3720. echo "sixes =  $sixes"
  3721. echo
  3722. }
  3723. function update_count()
  3724. {
  3725. case "$1" in
  3726.   0) let "ones += 1";;   # Since die has no "zero", this corresponds to 1.
  3727.   1) let "twos += 1";;   # And this to 2, etc.
  3728.   2) let "threes += 1";;
  3729.   3) let "fours += 1";;
  3730.   4) let "fives += 1";;
  3731.   5) let "sixes += 1";;
  3732. esac
  3733. }
  3734. echo
  3735. while [ "$throw" -lt "$MAXTHROWS" ]
  3736. do
  3737.   let "die1 = RANDOM % $PIPS"
  3738.   update_count $die1
  3739.   let "throw += 1"
  3740. done
  3741. print_result
  3742. echo "Out of a total of "$MAXTHROWS" rolls."
  3743. echo "Change \"MAXTHROWS=1000\" if you want a different number of rolls."
  3744. }
  3745.  
  3746.  
  3747.  
  3748. ##################################################
  3749. # Backup a file with a date-time stamp       #
  3750. ##################################################
  3751.  
  3752. # Usage "bu filename.txt"
  3753. function bu() { cp $1 ${1}-`date +%Y%m%d%H%M`.backup ; }
  3754.  
  3755.  
  3756.  
  3757. function buf() { cp -v $1 ${1/${1%%.*}/$f-$(date +"%Y%m%d_%H%M%S")}; }
  3758.  
  3759.  
  3760.  
  3761. ##################################################
  3762. # Extract a file and cd into the new folder  #
  3763. ##################################################
  3764.  
  3765. function build()
  3766. {
  3767.    extract "$1" && cd
  3768. }
  3769.  
  3770.  
  3771.  
  3772. ##################################################
  3773. # Needs fixing                   #
  3774. ##################################################
  3775.  
  3776. function build_() {
  3777. args=($@)
  3778. args[0]=
  3779. reset
  3780. tcc -o $1 ${1}.c ${args[@]}
  3781. if [ $? -eq 0 ]; then
  3782. ./$1;
  3783. fi
  3784. }
  3785.  
  3786.  
  3787.  
  3788. ##################################################
  3789. # Buffer in order to avoir mistakes with     #
  3790. # redirections that empty your files         #
  3791. ##################################################
  3792.  
  3793. function buffer() { tty -s && return; tmp=$(mktemp); cat > "${tmp}"; if [ -n "$1" ] && ( ( [ -f "$1" ] && [ -w "$1" ] ) || ( ! [ -a "$1" ] && [ -w "$(dirname "$1")" ] ) ); then mv -f "${tmp}" "$1"; else echo "Can't write in \"$1\""; rm -f "${tmp}"; fi }
  3794.  
  3795.  
  3796.  
  3797. ##################################################
  3798. # Generate a case-insensitive pattern        #
  3799. ##################################################
  3800.  
  3801. function casepat() { perl -pe 's/([a-zA-Z])/sprintf("[%s%s]",uc($1),$1)/ge' ; }
  3802.  
  3803.  
  3804.  
  3805. ##################################################
  3806. # Concatenate PDF files              #
  3807. ##################################################
  3808.  
  3809. ###### e.g. cat_pdfs -o combined.pdf file1.pdf file2.pdf file3.pdf
  3810. function cat_pdfs() { python '/System/Library/Automator/Combine PDF Pages.action/Contents/Resources/join.py' "$@" ; }
  3811.  
  3812.  
  3813.  
  3814. ##################################################
  3815. # Copy & paste files and folders from the    #
  3816. # command line                   #
  3817. ##################################################
  3818.  
  3819. ###### Usage: "ccopy FILE/FOLDER#1 FILE/FOLDER#2 FILE/FOLDER#3 FILE/FOLDER#4 ..."
  3820. # Note: You must 'cd' into the folder first ("whatever" works, while "~/myfolder/whatever" doesn't)
  3821. function ccopy() { for i in $*; do cp -a $i /tmp/ccopy.$i; done }
  3822. alias cpaste="ls -d /tmp/ccopy* | sed 's|[^\.]*.\.||' | xargs -I % mv /tmp/ccopy.% ./%"
  3823.  
  3824.  
  3825.  
  3826. ##################################################
  3827. # Print working directory after a cd.        #
  3828. ##################################################
  3829.  
  3830. # function cd() {
  3831. #     if [[ $@ == '-' ]]; then
  3832. #         builtin cd "$@" > /dev/null  # We'll handle pwd.
  3833. #     else
  3834. #         builtin cd "$@"
  3835. #     fi
  3836. #     echo -e "   \033[1;30m"`pwd`"\033[0m"
  3837. # }
  3838.  
  3839.  
  3840.  
  3841. ##################################################
  3842. # Change directory and list files        #
  3843. ##################################################
  3844.  
  3845. function cds() {
  3846.     # only change directory if a directory is specified
  3847.     [ -n "${1}" ] && cd $1
  3848.     lls
  3849. }
  3850.  
  3851.  
  3852.  
  3853. ##################################################
  3854. # Analyze your bash usage            #
  3855. ##################################################
  3856.  
  3857. function check_()
  3858. {
  3859. cut -f1 -d" " .bash_history | sort | uniq -c | sort -nr | head -n 30
  3860. }
  3861.  
  3862.  
  3863.  
  3864. ##################################################
  3865. # Checksum                   #
  3866. ##################################################
  3867.  
  3868. function checksum()
  3869. # copyright 2007 - 2010 Christopher Bratusek
  3870. {
  3871.     action=$1
  3872.     shift
  3873.     if [[ ( $action == "-c" || $action == "--check" ) && $1 == *.* ]]; then
  3874.         type="${1/*./}"
  3875.     else    type=$1
  3876.         shift
  3877.     fi
  3878.     case $type in
  3879.         md5 )
  3880.             checktool=md5sum
  3881.         ;;
  3882.         sha1 | sha )
  3883.             checktool=sha1sum
  3884.         ;;
  3885.         sha224 )
  3886.             checktool=sha224sum
  3887.         ;;
  3888.         sha256 )
  3889.             checktool=sha256sum
  3890.         ;;
  3891.         sha384 )
  3892.             checktool=sha384sum
  3893.         ;;
  3894.         sha512 )
  3895.             checktool=sha512sum
  3896.         ;;
  3897.     esac
  3898.     case $action in
  3899.         -g | --generate )
  3900.             for file in "${@}"; do
  3901.                 $checktool "${file}" > "${file}".$type
  3902.             done
  3903.         ;;
  3904.         -c | --check )
  3905.             for file in "${@}"; do
  3906.                 if [[ "${file}" == *.$type ]]; then
  3907.                     $checktool --check "${file}"
  3908.                 else    $checktool --check "${file}".$type
  3909.                 fi
  3910.             done
  3911.         ;;
  3912.         -h | --help )
  3913.         ;;
  3914.     esac
  3915. }
  3916.  
  3917.  
  3918.  
  3919. ###### MD5 checksum
  3920. function md5()
  3921. {
  3922.     echo -n $@ | md5sum
  3923. }
  3924.  
  3925.  
  3926.  
  3927. ###### Encode a string in md5 hash of 32 characters
  3928. # You can short the length with the second parameter.
  3929. #  @param string $1 string (required)
  3930. #  @param integer $2 length (option, default: 32)
  3931. #  @return string
  3932. #  @example:    md5 "Hello World" 8
  3933. function md5_() {
  3934.       local length=${2:-32}
  3935.       local string=$( echo "$1" | md5sum | awk '{ print $1 }' )
  3936.       echo ${string:0:${length}}
  3937. }
  3938.  
  3939.  
  3940.  
  3941. ##################################################
  3942. # Mount/unmount CIFS shares; pseudo-         #
  3943. # replacement for smbmount           #
  3944. ##################################################
  3945.  
  3946. ######   $1 = remote share name in form of //server/share
  3947. #   $2 = local mount point
  3948. function cifsmount() { sudo mount -t cifs -o username=${USER},uid=${UID},gid=${GROUPS} $1 $2; }
  3949.  
  3950.  
  3951.  
  3952. function cifsumount() { sudo umount $1; }
  3953.  
  3954.  
  3955.  
  3956. ##################################################
  3957. # Network information and IP address stuff   #
  3958. ##################################################
  3959.  
  3960. ###### clear iptables rules safely
  3961. function clearIptables()
  3962. {
  3963. iptables -P INPUT ACCEPT; iptables -P FORWARD ACCEPT; iptables -P OUTPUT ACCEPT; iptables -F; iptables -X; iptables -L
  3964. }
  3965.  
  3966.  
  3967.  
  3968. ###### find an unused unprivileged TCP port
  3969. function findtcp()
  3970. {
  3971. (netstat  -atn | awk '{printf "%s\n%s\n", $4, $4}' | grep -oE '[0-9]*$'; seq 32768 61000) | sort -n | uniq -u | head -n 1
  3972. }
  3973.  
  3974.  
  3975.  
  3976. ###### geoip lookup (need geoip database: sudo apt-get install geoip-bin)
  3977. function geoip() {
  3978. geoiplookup $1
  3979. }
  3980.  
  3981.  
  3982.  
  3983. ###### geoip information
  3984. # requires 'html2text': sudo apt-get install html2text
  3985. function geoiplookup() { curl -A "Mozilla/5.0" -s "http://www.geody.com/geoip.php?ip=$1" | grep "^IP.*$1" | html2text; }
  3986.  
  3987.  
  3988.  
  3989. ###### get IP address of a given interface
  3990. # Example: getip lo
  3991. # Example: getip eth0   # this is the default
  3992. function getip()        { lynx -dump http://whatismyip.org/; }
  3993.  
  3994.  
  3995.  
  3996. ###### display private IP
  3997. function ippriv()
  3998. {
  3999.     ifconfig eth0|grep "inet adr"|awk '{print $2}'|awk -F ':' '{print $2}'
  4000. }
  4001.  
  4002.  
  4003.  
  4004. ###### ifconfig connection check
  4005. function ips()
  4006. {
  4007.     if [ "$OS" = "Linux" ]; then
  4008.         for i in $( /sbin/ifconfig | grep ^e | awk '{print $1}' | sed 's/://' ); do echo -n "$i: ";  /sbin/ifconfig $i | perl -nle'/dr:(\S+)/ && print $1'; done
  4009.     elif [ "$OS" = "Darwin" ]; then
  4010.         for i in $( /sbin/ifconfig | grep ^e | awk '{print $1}' | sed 's/://' ); do echo -n "$i: ";  /sbin/ifconfig $i | perl -nle'/inet (\S+)/ && print $1'; done
  4011.     fi
  4012. }
  4013.  
  4014.  
  4015.  
  4016. ###### geolocate a given IP address
  4017. function ip2loc() { wget -qO - www.ip2location.com/$1 | grep "<span id=\"dgLookup__ctl2_lblICountry\">" | sed 's/<[^>]*>//g; s/^[\t]*//; s/&quot;/"/g; s/</</g; s/>/>/g; s/&amp;/\&/g'; }
  4018.  
  4019.  
  4020.  
  4021. ###### myip - finds your current IP if your connected to the internet
  4022. function myip()
  4023. {
  4024. lynx -dump -hiddenlinks=ignore -nolist http://checkip.dyndns.org:8245/ | awk '{ print $4 }' | sed '/^$/d; s/^[ ]*//g; s/[ ]*$//g'
  4025. }
  4026.  
  4027.  
  4028.  
  4029. ###### netinfo - shows network information for your system
  4030. function netinfo()
  4031. {
  4032. echo "--------------- Network Information ---------------"
  4033. /sbin/ifconfig | awk /'inet addr/ {print $2}'
  4034. /sbin/ifconfig | awk /'Bcast/ {print $3}'
  4035. /sbin/ifconfig | awk /'inet addr/ {print $4}'
  4036. /sbin/ifconfig | awk /'HWaddr/ {print $4,$5}'
  4037. myip=`lynx -dump -hiddenlinks=ignore -nolist http://checkip.dyndns.org:8245/ | sed '/^$/d; s/^[ ]*//g; s/[ ]*$//g' `
  4038. echo "${myip}"
  4039. echo "---------------------------------------------------"
  4040. }
  4041.  
  4042.  
  4043.  
  4044. ###### show ip
  4045. # copyright 2007 - 2010 Christopher Bratusek
  4046. function show_ip()
  4047. {
  4048.     case $1 in
  4049.         *help | "" )
  4050.             echo -e "\n${ewhite}Usage:\n"
  4051.             echo -e "${eorange}show_ip${ewhite} |${egreen} <interface> ${eiceblue}[show ip-address for <interface>]\
  4052.             \n${eorange}show_ip${ewhite} |${egreen} external${eiceblue} [show external ip address]\n"
  4053.             tput sgr0
  4054.         ;;
  4055.         *external )
  4056.             wget -q -O - http://showip.spamt.net/
  4057.         ;;
  4058.         * )
  4059.             LANG=C /sbin/ifconfig $1 | grep 'inet addr:' | cut -d: -f2 | gawk '{ print $1}'
  4060.         ;;
  4061.     esac
  4062. }
  4063.  
  4064.  
  4065.  
  4066. ###### display the ttl of a hostname in a human readable form
  4067. function ttl()
  4068. {
  4069. /usr/sbin/timetrans -count $(dig +noquestion +noadditional +noauthority $1 | grep "^$1" | awk '{print $2}')
  4070. }
  4071.  
  4072.  
  4073.  
  4074. ###### show Url information
  4075. # Usage:    url-info "ur"
  4076. # This script is part of nixCraft shell script collection (NSSC)
  4077. # Visit http://bash.cyberciti.biz/ for more information.
  4078. # Modified by Silviu Silaghi (http://docs.opensourcesolutions.ro) to handle
  4079. # more ip adresses on the domains on which this is available (eg google.com or yahoo.com)
  4080. # Last updated on Sep/06/2010
  4081. function url-info()
  4082. {
  4083. doms=$@
  4084. if [ $# -eq 0 ]; then
  4085. echo -e "No domain given\nTry $0 domain.com domain2.org anyotherdomain.net"
  4086. fi
  4087. for i in $doms; do
  4088. _ip=$(host $i|grep 'has address'|awk {'print $4'})
  4089. if [ "$_ip" == "" ]; then
  4090. echo -e "\nERROR: $i DNS error or not a valid domain\n"
  4091. continue
  4092. fi
  4093. ip=`echo ${_ip[*]}|tr " " "|"`
  4094. echo -e "\nInformation for domain: $i [ $ip ]\nQuerying individual IPs"
  4095.  for j in ${_ip[*]}; do
  4096. echo -e "\n$j results:"
  4097. whois $j |egrep -w 'OrgName:|City:|Country:|OriginAS:|NetRange:'
  4098. done
  4099. done
  4100. }
  4101.  
  4102.  
  4103.  
  4104. ##################################################
  4105. # Commandlinefu.com and Shell-fu.org stuff   #
  4106. ##################################################
  4107.  
  4108. ###### Search commandlinefu.com from the command line
  4109. # using the API
  4110. # Usage: cmdfu hello world
  4111. function cmdfu() { curl "http://www.commandlinefu.com/commands/matching/$@/$(echo -n $@ | openssl base64)/plaintext"; }
  4112.  
  4113.  
  4114.  
  4115. ###### automatically downloads all commands from http://www.commandlinefu.com into a single text file
  4116. alias cmdfu_dl='mkdir /tmp/commandlinefu && cd /tmp/commandlinefu && curl -O http://www.commandlinefu.com/commands/browse/sort-by-votes/plaintext/[0-2400:25] && ls -1 | sort -n | while read mork ; do cat $mork >> commandlinefu.txt ; ls -ald $mork; done && mv commandlinefu.txt $HOME && rm -rf /tmp/commandlinefu'
  4117.  
  4118.  
  4119.  
  4120. ###### find a CommandlineFu users average command rating
  4121. function cmdfu_rating()
  4122. {
  4123. wget -qO- www.commandlinefu.com/commands/by/PhillipNordwall | awk -F\> '/class="num-votes"/{S+=$2; I++}END{print S/I}'
  4124. }
  4125.  
  4126.  
  4127.  
  4128. function cmdfu_rating_()
  4129. {
  4130. curl -s www.commandlinefu.com/commands/by/PhillipNordwall | awk -F\> '/class="num-votes"/{S+=$2; I++}END{print S/I}'
  4131. }
  4132.  
  4133.  
  4134.  
  4135. ###### command examples from shell-fu
  4136. function examples() { lynx -width=$COLUMNS -nonumbers -dump "http://www.shell-fu.org/lister.php?tag=$1" | \
  4137. sed -n '/^[a-zA-Z]/,$p' | egrep -v '^http|^javas|View Comm|HIDE|] \+|to Share|^ +\*|^ +[HV][a-z]* l|^ .*efu.*ep.*!$' | \
  4138. sed -e '/^  *__*/N;s/\n$//g' | less -r; }
  4139.  
  4140.  
  4141.  
  4142. ###### fuman, an alternative to the 'man' command that shows commandlinefu.com examples
  4143. function fuman() { lynx -width=$COLUMNS -nonumbers -dump "http://www.commandlinefu.com/commands/using/$1" |sed '/Add to favourites/,/This is sample output/!d' |sed 's/ *Add to favourites/----/' |less -r; }
  4144.  
  4145.  
  4146.  
  4147. ###### Prepare a commandlinefu command
  4148. function goclf()
  4149. {
  4150. type "$1" | sed '1d' | tr -d "\n" | tr -s '[:space:]'; echo
  4151. }
  4152.  
  4153.  
  4154.  
  4155. ##################################################
  4156. # Sets custom Catalog Number ID3 tag for all     #
  4157. # MP3 files in current directory         #
  4158. ##################################################
  4159.  
  4160. ###### $1 = catalog number
  4161. function cn() { for i in *.mp3; do id3v2 --TXXX "Catalog Number":"$1" "$i"; done; }
  4162.  
  4163.  
  4164.  
  4165. ##################################################
  4166. # Quick reference color charts  & color stuff    #
  4167. ##################################################
  4168.  
  4169. ###### shows a gui color chart (requires python-gtkmozembed:
  4170. # sudo apt-get install python-gtkmozembed)
  4171. function color-picker()
  4172. {
  4173. echo "When you are finished, press "Control C" to continue..."
  4174. cat > "/tmp/color-picker.py" <<"End-of-message"
  4175. #!/usr/bin/python
  4176. import os
  4177. import pygtk
  4178. pygtk.require('2.0')
  4179. import gtk
  4180. import gtkmozembed
  4181. homedir = os.path.expanduser('~')
  4182. try:
  4183.     from win32com.shell import shellcon, shell
  4184.     homedir = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0)
  4185. except ImportError:
  4186.     homedir = os.path.expanduser("~/.gnome2/nautilus-scripts/.colorchart/view.html")
  4187. class ColorChart:
  4188.     def __init__(self):
  4189.                 self.moz = gtkmozembed.MozEmbed()
  4190.         box = gtk.VBox(False,0)
  4191.         win = gtk.Window()
  4192.         win.add(box)
  4193.         hbox = gtk.HBox(False,0)
  4194.                 box.pack_start(hbox,False,False)
  4195.                 hbox.show()
  4196.         box.pack_start(self.moz,True,True,0)
  4197.                 self.moz.show()
  4198.         self.moz.load_url(homedir)
  4199.                 self.moz.set_size_request(650,550)
  4200.         title=self.moz.get_title()
  4201.         win.set_title("RGB/HEX Color Picker")
  4202.         win.show_all()
  4203. if __name__ == "__main__":
  4204.     ColorChart()
  4205.     gtk.main()
  4206. End-of-message
  4207. chmod +x "/tmp/color-picker.py"
  4208. /usr/bin/python "/tmp/color-picker.py"
  4209. rm "/tmp/color-picker.py"
  4210. }
  4211.  
  4212.  
  4213.  
  4214. ###### takes a name of a color and some text and then echoes out the text in the named color
  4215. # Usage:    colorize_text "color" "whatever text"
  4216. function colorize-text()
  4217. {
  4218. b='[0;30m'
  4219. # Implement command-line options
  4220. while getopts "nr" opt
  4221.  do
  4222.   case $opt in
  4223.    n  )  o='-n' ;;
  4224.    r  )  b=''   ;;
  4225.   esac
  4226.  done
  4227. shift $(($OPTIND - 1))
  4228. # Set variables
  4229. col=$1
  4230. shift
  4231. text="$*"
  4232. # Set a to console color code
  4233. case $col in
  4234.  'black'  ) a='[0;30m' ;;
  4235.  'blue'   ) a='[0;34m' ;;
  4236.  'green'  ) a='[0;32m' ;;
  4237.  'cyan'   ) a='[0;36m' ;;
  4238.  'red'    ) a='[0;31m' ;;
  4239.  'purple' ) a='[0;35m' ;;
  4240.  'brown'  ) a='[0;33m' ;;
  4241.  'ltgray' ) a='[0;37m' ;;
  4242.  'white'  ) a='[1;30m' ;;
  4243.  'ltblue' ) a='[1;34m' ;;
  4244.  'ltgreen') a='[1;32m' ;;
  4245.  'ltcyan' ) a='[1;36m' ;;
  4246.  'ltred'  ) a='[1;31m' ;;
  4247.  'pink'   ) a='[1;35m' ;;
  4248.  'yellow' ) a='[1;33m' ;;
  4249.  'gray'   ) a='[1;37m' ;;
  4250. esac
  4251. # Display text in designated color, no newline
  4252. echo -en "\033$a$text"
  4253. # If 'b' switch not on, restore color to black
  4254. if [ -n $b ]
  4255.  then
  4256.   echo -en "\033$b"
  4257. fi
  4258. # If 'n' switch on, do not display final newline
  4259. # otherwise output newline
  4260. echo $o
  4261. }
  4262.  
  4263.  
  4264.  
  4265. ###### shows the colors in a kewl way...partially stolen from HH
  4266. function colors()
  4267. {
  4268.        # Display ANSI colours.
  4269.     esc="\033["
  4270.     echo -e "\t  40\t   41\t   42\t    43\t      44       45\t46\t 47"
  4271.     for fore in 30 31 32 33 34 35 36 37; do
  4272.         line1="$fore  "
  4273.         line2="    "
  4274.         for back in 40 41 42 43 44 45 46 47; do
  4275.             line1="${line1}${esc}${back};${fore}m Normal  ${esc}0m"
  4276.             line2="${line2}${esc}${back};${fore};1m Bold    ${esc}0m"
  4277.         done
  4278.         echo -e "$line1\n$line2"
  4279.     done
  4280.     echo ""
  4281.     echo "# Example:"
  4282.     echo "#"
  4283.     echo "# Type a Blinkin TJEENARE in Swedens colours (Yellow on Blue)"
  4284.     echo "#"
  4285.     echo "#           ESC"
  4286.     echo "#            |  CD"
  4287.     echo "#            |  | CD2"
  4288.     echo "#            |  | | FG"
  4289.     echo "#            |  | | |  BG + m"
  4290.     echo "#            |  | | |  |         END-CD"
  4291.     echo "#            |  | | |  |            |"
  4292.     echo "# echo -e '\033[1;5;33;44mTJEENARE\033[0m'"
  4293.     echo "#"
  4294.     echo "# Sedika Signing off for now ;->"
  4295. }
  4296.  
  4297.  
  4298.  
  4299. ###### displays all 256 possible background colors, using ANSI escape sequences.
  4300. # author: Chetankumar Phulpagare
  4301. # used in ABS Guide with permission.
  4302. function colors2()
  4303. {
  4304. T1=8
  4305. T2=6
  4306. T3=36
  4307. offset=0
  4308. for num1 in {0..7}
  4309. do {
  4310.    for num2 in {0,1}
  4311.        do {
  4312.           shownum=`echo "$offset + $T1 * ${num2} + $num1" | bc`
  4313.           echo -en "\E[0;48;5;${shownum}m color ${shownum} \E[0m"
  4314.           }
  4315.        done
  4316.    echo
  4317.    }
  4318. done
  4319. offset=16
  4320. for num1 in {0..5}
  4321. do {
  4322.    for num2 in {0..5}
  4323.        do {
  4324.           for num3 in {0..5}
  4325.               do {
  4326.                  shownum=`echo "$offset + $T2 * ${num3} \
  4327.                 + $num2 + $T3 * ${num1}" | bc`
  4328.                  echo -en "\E[0;48;5;${shownum}m color ${shownum} \E[0m"
  4329.                  }
  4330.                done
  4331.           echo
  4332.           }
  4333.        done
  4334. }
  4335. done
  4336. offset=232
  4337. for num1 in {0..23}
  4338. do {
  4339.    shownum=`expr $offset + $num1`
  4340.    echo -en "\E[0;48;5;${shownum}m ${shownum}\E[0m"
  4341. }
  4342. done
  4343. echo
  4344. }
  4345.  
  4346.  
  4347.  
  4348. ###### print all 256 colors for testing TERM or for a quick reference
  4349. # show numerical values for each of the 256 colors in bash
  4350. function colors2nums()
  4351. {
  4352. for code in {0..255}; do echo -e "\e[38;05;${code}m $code: Test"; done
  4353. }
  4354.  
  4355.  
  4356.  
  4357. ###### replaces a color in PDF document (useful for removing dark background for printing)
  4358. # usage:    remove_color input.pdf output.pdf
  4359. function uncolorpdf()
  4360. {
  4361. convert -density 300 "$1" -fill "rgb(255,255,255)" -opaque "rgb(0,0,0)" "$2"
  4362. }
  4363.  
  4364.  
  4365.  
  4366. ##################################################
  4367. # View daily comics (set on Viewnior as image    #
  4368. # viewer...can use 'eog' or whatever instead)    #
  4369. ##################################################
  4370.  
  4371. function comics() {
  4372.     # xkcd
  4373.     XKCD_FILE="/tmp/xkcd"
  4374.     wget -q $(curl -s http://xkcd.com/ | sed -n 's/<h3>Image URL.*: \(.*\)<\/h3>/\1/p') -O $XKCD_FILE
  4375.     # Geek and Poke
  4376.     GAP_FILE="/tmp/geekandpoke"
  4377.     wget -q $(lynx --dump 'http://geekandpoke.typepad.com/' | grep '\/.a\/' | grep '\-pi' | head -n 1 | awk '{print $2}') -O $GAP_FILE
  4378.     viewnior $XKCD_FILE
  4379.     viewnior $GAP_FILE
  4380. }
  4381.  
  4382.  
  4383.  
  4384. ##################################################
  4385. # Convert to avi                 #
  4386. ##################################################
  4387.  
  4388. function conv2avi() {
  4389.     # copyright 2007 - 2010 Christopher Bratusek
  4390.     if [[ $(which mencoder-mt) != "" ]]; then
  4391.     mencoder-mt "$1" -lavdopts threads=8 \
  4392.       -ovc xvid -xvidencopts fixed_quant=4 -of avi \
  4393.       -oac mp3lame -lameopts vbr=3 \
  4394.       -o "$1".avi
  4395.     else
  4396.     mencoder "$1" -lavdopts \
  4397.       -ovc xvid -xvidencopts fixed_quant=4 -of avi \
  4398.       -oac mp3lame -lameopts vbr=3 \
  4399.       -o "$1".avi
  4400.     fi
  4401. }
  4402.  
  4403.  
  4404.  
  4405. ##################################################
  4406. # Get name of app that created a corefile    #
  4407. ##################################################
  4408.  
  4409. function corename()
  4410. {
  4411.     for file ; do
  4412.         echo -n $file : ; gdb --core=$file --batch | head -1
  4413.     done
  4414. }
  4415.  
  4416.  
  4417.  
  4418. ##################################################
  4419. # Count opening and closing braces in a string   #
  4420. ##################################################
  4421.  
  4422. function countbraces() { COUNT_OPENING=$(echo $1 | grep -o "(" | wc -l); COUNT_CLOSING=$(echo $1 | grep -o ")" | wc -l); echo Opening: $COUNT_OPENING; echo Closing: $COUNT_CLOSING; }
  4423.  
  4424.  
  4425.  
  4426. ##################################################
  4427. # Count files in current directory       #
  4428. ##################################################
  4429.  
  4430. function count_files()
  4431. # copyright 2007 - 2010 Christopher Bratusek
  4432. {
  4433.     case $1 in
  4434.         *+h)
  4435.             echo $(($(ls --color=no -1 -la . | grep -v ^l | wc -l)-1))
  4436.         ;;
  4437.         *-h)
  4438.             echo $(($(ls --color=no -1 -l . | grep -v ^l | wc -l)-1))
  4439.         ;;
  4440.         *+d)
  4441.             echo $(($(ls --color=no -1 -la . | grep -v ^- | wc -l)-1))
  4442.         ;;
  4443.         *-d)
  4444.             echo $(($(ls --color=no -1 -l . | grep -v ^- | wc -l)-1))
  4445.         ;;
  4446.         *+f)
  4447.             echo $(($(ls --color=no -1 -la . | grep -v ^d | wc -l)-1))
  4448.         ;;
  4449.         *-f)
  4450.             echo $(($(ls --color=no -1 -l . | grep -v ^d | wc -l)-1))
  4451.         ;;
  4452.         *)
  4453.             echo -e "\n${ewhite}Usage:"
  4454.             echo -e "\n${eorange}count_files${ewhite} | ${egreen}+h ${eiceblue}[count files and folders - include hidden ones] \
  4455.             \n${eorange}count_files${ewhite} | ${egreen}-h ${eiceblue}[count files and folders - exclude hidden ones] \
  4456.             \n${eorange}count_files${ewhite} | ${egreen}+d ${eiceblue}[count folders - include hidden ones] \
  4457.             \n${eorange}count_files${ewhite} | ${egreen}-d ${eiceblue}[count folders - exclude hidden ones] \
  4458.             \n${eorange}count_files${ewhite} | ${egreen}+f ${eiceblue}[count files - include hidden ones] \
  4459.             \n${eorange}count_files${ewhite} | ${egreen}-f ${eiceblue}[count files - exclude hidden ones]\n"
  4460.             tput sgr0
  4461.         ;;
  4462.     esac
  4463. }
  4464.  
  4465.  
  4466.  
  4467. ##################################################
  4468. # Count processes that are running       #
  4469. ##################################################
  4470.  
  4471. function count_processes()
  4472. # copyright 2007 - 2010 Christopher Bratusek
  4473. {
  4474.     case $1 in
  4475.         *help )
  4476.             echo -e "\n${ewhite}Usage:"
  4477.             echo -e "\n${eorange}count_processes${ewhite} | ${egreen}! no options !\n"
  4478.             tput sgr0
  4479.         ;;
  4480.         * )
  4481.             procs=$(ps ax | wc -l | awk '{print $1}')
  4482.             if [[ $procs -lt 10 ]]; then
  4483.                 echo "000$procs"
  4484.             elif [[ $procs -lt 100 ]]; then
  4485.                 echo "00$procs"
  4486.             elif [[ $procs -lt 1000 ]]; then
  4487.                 echo "0$procs"
  4488.             fi
  4489.         ;;
  4490.     esac
  4491. }
  4492.  
  4493.  
  4494.  
  4495. ##################################################
  4496. # Copies currently played song in Audacious to   #
  4497. # selected directory                 #
  4498. ##################################################
  4499.  
  4500. function cp_mp3_to() { PID=`pidof audacious2`; FILEPATH=`lsof -p $PID| grep mp3| sed s/[^\/]*//`; cp "$FILEPATH" "$1"; }
  4501.  
  4502.  
  4503.  
  4504. ##################################################
  4505. # Cp with progress bar (using pv)        #
  4506. ##################################################
  4507.  
  4508. function cp_p() {
  4509.     if [ `echo "$2" | grep ".*\/$"` ]
  4510.     then
  4511.         pv "$1" > "$2""$1"
  4512.     else
  4513.         pv "$1" > "$2"/"$1"
  4514.     fi
  4515. }
  4516.  
  4517.  
  4518.  
  4519. ##################################################
  4520. # Encryption / decryption            #
  4521. ##################################################
  4522.  
  4523. ###### do twice to decrypt
  4524. # copyright 2007 - 2010 Christopher Bratusek
  4525. function crypt() {
  4526.     if [[ -e "$1" ]]; then
  4527.         tr a-zA-Z n-za-mN-ZA-M < "$1" > "$1".crypt
  4528.         rm -f "$1"
  4529.         mv "$1".crypt "$1"
  4530.     fi
  4531. }
  4532.  
  4533.  
  4534.  
  4535. ###### basic encrypt / decrypt
  4536. # example: "encry filename" or "decry filename"
  4537. function encry()
  4538. {
  4539. gpg -ac --no-options "$1"
  4540. }
  4541.  
  4542.  
  4543.  
  4544. function decry()
  4545. {
  4546. gpg --no-options "$1"
  4547. }
  4548.  
  4549.  
  4550.  
  4551. ###### More advanced encryption / decryption
  4552. # example: "encrypt filename" or "decrypt filename"
  4553. function encrypt()
  4554. {
  4555. # Author: Martin Langasek <cz4160@gmail.com>
  4556. case $LANG in
  4557.   cs* )
  4558.     err_title="Chyba"
  4559.     err_files="Neoznačen soubor"
  4560.     encrypt="Å ifrovat"
  4561.     decrypt="DeÅ¡ifrovat"
  4562.     file_msg="soubor:"
  4563.     pass_msg="Vložte heslo";;
  4564.   * )
  4565.     err_title="Error"
  4566.     err_files="No file selected"
  4567.     encrypt="Encrypt"
  4568.     decrypt="Decrypt"
  4569.     file_msg="file:"
  4570.     pass_msg="Enter passphrase";;
  4571. esac
  4572. if [ "$1" != "" ]
  4573. then
  4574.   i=1
  4575.   file=`echo "$1" | sed ''$i'!d'`
  4576.   while [ "$file" != "" ]
  4577.   do
  4578.     ext=`echo "$file" | grep [.]gpg$ 2>&1`
  4579.     if [ "$ext" != "" ]
  4580.     then
  4581.       pass_decrypt=`zenity --entry --entry-text "$pass_decrypt" --hide-text --title "$pass_msg" --text "$decrypt $file_msg ${file##*/}" "" 2>&1`
  4582.       if [ "$pass_decrypt" != "" ]
  4583.       then
  4584.         output=${file%.*}
  4585.         echo "$pass_decrypt" | gpg -o "$output" --batch --passphrase-fd 0 -d "$file"
  4586.       fi
  4587.     else
  4588.       pass_encrypt=`zenity --entry --hide-text --entry-text "$pass_encrypt" --title "$pass_msg" --text "$encrypt $file_msg ${file##*/}" "" 2>&1`
  4589.       if [ "$pass_encrypt" != "" ]
  4590.       then
  4591.         echo "$pass_encrypt" | gpg --batch --passphrase-fd 0 --cipher-algo aes256 -c "$file"
  4592.       fi
  4593.     fi
  4594.     i=$(($i+1))
  4595.     file=`echo "$1" | sed ''$i'!d'`
  4596.   done
  4597. else
  4598.   zenity --error --title "$err_title" --text "$err_files"
  4599. fi
  4600. }
  4601.  
  4602.  
  4603.  
  4604. alias decrypt='encrypt'
  4605.  
  4606.  
  4607.  
  4608. ###### rot13 ("rotate alphabet 13 places" Caesar-cypher encryption)
  4609. function rot13()
  4610. {
  4611.     if [ $# -lt 1 ] || [ $# -gt 1 ]; then
  4612.         echo "Seriously?  You don't know what rot13 does?"
  4613.     else
  4614.         echo $@ | tr A-Za-z N-ZA-Mn-za-m
  4615.     fi
  4616. }
  4617.  
  4618.  
  4619.  
  4620. ###### rot47 ("rotate ASCII characters from '!" to '~' 47 places" Caesar-cypher encryption)
  4621. function rot47()
  4622. {
  4623.     if [ $# -lt 1 ] || [ $# -gt 1 ]; then
  4624.         echo "Seriously?  You don't know what rot47 does?"
  4625.     else
  4626.         echo $@ | tr '!-~' 'P-~!-O'
  4627.     fi
  4628. }
  4629.  
  4630.  
  4631.  
  4632. ##################################################
  4633. # Google searching               #
  4634. ##################################################
  4635.  
  4636. ###### convert currencies
  4637. # usage:    currency_convert 1 usd eur
  4638. # for currency shorthand: http://www.xe.com/currency/
  4639. function currency_convert() { wget -qO- "http://www.google.com/finance/converter?a=$1&from=$2&to=$3&hl=es" | sed '/res/!d;s/<[^>]*>//g'; }
  4640.  
  4641.  
  4642.  
  4643. function currency_convert_help() {
  4644. cat <<EOF
  4645. AED - Emirati Dirham
  4646. AFN - Afghan Afghani
  4647. ALL - Albanian Lek
  4648. AMD - Armenian Dram
  4649. ANG - Dutch Guilder
  4650. AOA - Angolan Kwanza
  4651. ARS - Argentine Peso
  4652. AUD - Australian Dollar
  4653. AWG - Aruban or Dutch Guilder
  4654. AZN - Azerbaijani New Manat
  4655. BAM - Bosnian Convertible Marka
  4656. BBD - Barbadian or Bajan Dollar
  4657. BDT - Bangladeshi Taka
  4658. BGN - Bulgarian Lev
  4659. BHD - Bahraini Dinar
  4660. BIF - Burundian Franc
  4661. BMD - Bermudian Dollar
  4662. BND - Bruneian Dollar
  4663. BOB - Bolivian Boliviano
  4664. BRL - Brazilian Real
  4665. BSD - Bahamian Dollar
  4666. BTN - Bhutanese Ngultrum
  4667. BWP - Batswana Pula
  4668. BYR - Belarusian Ruble
  4669. BZD - Belizean Dollar
  4670. CAD - Canadian Dollar
  4671. CDF - Congolese Franc
  4672. CHF - Swiss Franc
  4673. CLP - Chilean Peso
  4674. CNY - Chinese Yuan Renminbi
  4675. COP - Colombian Peso
  4676. CRC - Costa Rican Colon
  4677. CUC - Cuban Convertible Peso
  4678. CUP - Cuban Peso
  4679. CVE - Cape Verdean Escudo
  4680. CZK - Czech Koruna
  4681. DJF - Djiboutian Franc
  4682. DKK - Danish Krone
  4683. DOP - Dominican Peso
  4684. DZD - Algerian Dinar
  4685. EEK - Estonian Kroon
  4686. EGP - Egyptian Pound
  4687. ERN - Eritrean Nakfa
  4688. ETB - Ethiopian Birr
  4689. EUR - Euro
  4690. FJD - Fijian Dollar
  4691. FKP - Falkland Island Pound
  4692. GBP - British Pound
  4693. GEL - Georgian Lari
  4694. GGP - Guernsey Pound
  4695. GHS - Ghanaian Cedi
  4696. GIP - Gibraltar Pound
  4697. GMD - Gambian Dalasi
  4698. GNF - Guinean Franc
  4699. GTQ - Guatemalan Quetzal
  4700. GYD - Guyanese Dollar
  4701. HKD - Hong Kong Dollar
  4702. HNL - Honduran Lempira
  4703. HRK - Croatian Kuna
  4704. HTG - Haitian Gourde
  4705. HUF - Hungarian Forint
  4706. IDR - Indonesian Rupiah
  4707. ILS - Israeli Shekel
  4708. IMP - Isle of Man Pound
  4709. INR - Indian Rupee
  4710. IQD - Iraqi Dinar
  4711. IRR - Iranian Rial
  4712. ISK - Icelandic Krona
  4713. JEP - Jersey Pound
  4714. JMD - Jamaican Dollar
  4715. JOD - Jordanian Dinar
  4716. JPY - Japanese Yen
  4717. KES - Kenyan Shilling
  4718. KGS - Kyrgyzstani Som
  4719. KHR - Cambodian Riel
  4720. KMF - Comoran Franc
  4721. KPW - Korean Won
  4722. KRW - Korean Won
  4723. KWD - Kuwaiti Dinar
  4724. KYD - Caymanian Dollar
  4725. KZT - Kazakhstani Tenge
  4726. LAK - Lao or Laotian Kip
  4727. LBP - Lebanese Pound
  4728. LKR - Sri Lankan Rupee
  4729. LRD - Liberian Dollar
  4730. LSL - Basotho Loti
  4731. LTL - Lithuanian Litas
  4732. LVL - Latvian Lat
  4733. LYD - Libyan Dinar
  4734. MAD - Moroccan Dirham
  4735. MDL - Moldovan Leu
  4736. MGA - Malagasy Ariary
  4737. MKD - Macedonian Denar
  4738. MMK - Burmese Kyat
  4739. MNT - Mongolian Tughrik
  4740. MOP - Macau Pataca
  4741. MRO - Mauritian Ouguiya
  4742. MUR - Mauritian Rupee
  4743. MVR - Maldivian Rufiyaa
  4744. MWK - Malawian Kwacha
  4745. MXN - Mexican Peso
  4746. MYR - Malaysian Ringgit
  4747. MZN - Mozambican Metical
  4748. NAD - Namibian Dollar
  4749. NGN - Nigerian Naira
  4750. NIO - Nicaraguan Cordoba
  4751. NOK - Norwegian Krone
  4752. NPR - Nepalese Rupee
  4753. NZD - New Zealand Dollar
  4754. OMR - Omani Rial
  4755. PAB - Panamanian Balboa
  4756. PEN - Peruvian Nuevo Sol
  4757. PGK - Papua New Guinean Kina
  4758. PHP - Philippine Peso
  4759. PKR - Pakistani Rupee
  4760. PLN - Polish Zloty
  4761. PYG - Paraguayan Guarani
  4762. QAR - Qatari Riyal
  4763. RON - Romanian New Leu
  4764. RSD - Serbian Dinar
  4765. RUB - Russian Ruble
  4766. RWF - Rwandan Franc
  4767. SAR - Saudi or Saudi Arabian Riyal
  4768. SBD - Solomon Islander Dollar
  4769. SCR - Seychellois Rupee
  4770. SDG - Sudanese Pound
  4771. SEK - Swedish Krona
  4772. SGD - Singapore Dollar
  4773. SHP - Saint Helenian Pound
  4774. SLL - Sierra Leonean Leone
  4775. SOS - Somali Shilling
  4776. SPL - Seborgan Luigino
  4777. SRD - Surinamese Dollar
  4778. STD - Sao Tomean Dobra
  4779. SVC - Salvadoran Colon
  4780. SYP - Syrian Pound
  4781. SZL - Swazi Lilangeni
  4782. THB - Thai Baht
  4783. TJS - Tajikistani Somoni
  4784. TMT - Turkmenistani Manat
  4785. TND - Tunisian Dinar
  4786. TOP - Tongan Pa'anga
  4787. TRY - Turkish Lira
  4788. TTD - Trinidadian Dollar
  4789. TVD - Tuvaluan Dollar
  4790. TWD - Taiwan New Dollar
  4791. TZS - Tanzanian Shilling
  4792. UAH - Ukrainian Hryvna
  4793. UGX - Ugandan Shilling
  4794. USD - US Dollar
  4795. UYU - Uruguayan Peso
  4796. UZS - Uzbekistani Som
  4797. VEF - Venezuelan Bolivar Fuerte
  4798. VND - Vietnamese Dong
  4799. VUV - Ni-Vanuatu Vatu
  4800. WST - Samoan Tala
  4801. XAF - Central African CFA Franc BEAC
  4802. XCD - East Caribbean Dollar
  4803. XDR - IMF Special Drawing Rights
  4804. XOF - CFA Franc
  4805. XPF - CFP Franc
  4806. YER - Yemeni Rial
  4807. ZAR - South African Rand
  4808. ZMK - Zambian Kwacha
  4809. ZWD - Zimbabwean Dollar
  4810. EOF
  4811. }
  4812.  
  4813.  
  4814.  
  4815. ###### define a word - USAGE: define dog
  4816. function define() {
  4817.   local LNG=$(echo $LANG | cut -d '_' -f 1)
  4818.   local CHARSET=$(echo $LANG | cut -d '.' -f 2)
  4819.   lynx -accept_all_cookies -dump -hiddenlinks=ignore -nonumbers -assume_charset="$CHARSET" -display_charset="$CHARSET" "http://www.google.com/search?hl=${LNG}&q=define%3A+${1}&btnG=Google+Search" | grep -m 5 -C 2 -A 5 -w "*" > /tmp/define
  4820.   if [ ! -s /tmp/define ]; then
  4821.     echo "Sorry, google doesn't know this one..."
  4822.     rm -f /tmp/define
  4823.     return 1
  4824.   else
  4825.     cat /tmp/define | grep -v Search
  4826.     echo ""
  4827.   fi
  4828.   rm -f /tmp/define
  4829.   return 0
  4830. }
  4831.  
  4832.  
  4833.  
  4834. ###### detect language of a string
  4835. function detectlanguage() { curl -s "http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=$@" | sed 's/{"responseData": {"language":"\([^"]*\)".*/\1\n/'; }
  4836.  
  4837.  
  4838.  
  4839. ###### find a location's coordinates
  4840. # usage:    findlocation "Las Vegas, Nevada" = coordinates: [ -115.1728160, 36.1146460, 0 ]
  4841. function findlocation() { place=`echo $1 | sed 's/ /%20/g'` ; curl -s "http://maps.google.com/maps/geo?output=json&oe=utf-8&q=$place" | grep -e "address" -e "coordinates" | sed -e 's/^ *//' -e 's/"//g' -e 's/address/Full Address/';}
  4842.  
  4843.  
  4844.  
  4845. ###### Google search (example: google dog)
  4846. function google() {
  4847. firefox "http://www.google.com/search?&num=100&q=${@}" &
  4848. }
  4849.  
  4850.  
  4851.  
  4852. ###### translate a word using Google
  4853. # usage: translate <phrase> <output-language>
  4854. # example: translate "hello" es = hola (will auto-detect source language)
  4855. # for a list of language codes: http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
  4856. function translate() { wget -qO- "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=$1&langpair=%7C${2:-en}" | sed 's/.*{"translatedText":"\([^"]*\)".*/\1\n/'; }
  4857.  
  4858.  
  4859.  
  4860. function translate_help() {
  4861. cat <<EOF
  4862. Language    ISO
  4863. (Afan) Oromo    om
  4864. Abkhazian   ab
  4865. Afar        aa
  4866. Afrikaans   af
  4867. Albanian    sq
  4868. Amharic     am
  4869. Arabic      ar
  4870. Armenian    hy
  4871. Assamese    as
  4872. Aymara      ay
  4873. Azerbaijani az
  4874. Bashkir     ba
  4875. Basque      eu
  4876. Bengali     bn
  4877. Bhutani     dz
  4878. Bihari      bh
  4879. Bislama     bi
  4880. Breton      br
  4881. Bulgarian   bg
  4882. Burmese     my
  4883. Byelorussian    be
  4884. Cambodian   km
  4885. Catalan     ca
  4886. Chinese     zh
  4887. Corsican    co
  4888. Croatian    hr
  4889. Czech       cs
  4890. Danish      da
  4891. Dutch       nl
  4892. English     en
  4893. Esperanto   eo
  4894. Estonian    et
  4895. Faeroese    fo
  4896. Fiji        fj
  4897. Finnish     fi
  4898. French      fr
  4899. Frisian     fy
  4900. Galician    gl
  4901. Georgian    ka
  4902. German      de
  4903. Greek       el
  4904. Greenlandic kl
  4905. Guarani     gn
  4906. Gujarati    gu
  4907. Hausa       ha
  4908. Hebrew      he
  4909. (former iw)
  4910. Hindi       hi
  4911. Hungarian   hu
  4912. Icelandic   is
  4913. Indonesian  id
  4914. (former in)
  4915. Interlingua ia
  4916. Interlingue ie
  4917. Inupiak     ik
  4918. Inuktitut   iu
  4919. (Eskimo)
  4920. Irish       ga
  4921. Italian     it
  4922. Japanese    ja
  4923. Javanese    jw
  4924. Kannada     kn
  4925. Kashmiri    ks
  4926. Kazakh      kk
  4927. Kinyarwanda rw
  4928. Kirghiz     ky
  4929. Kirundi     rn
  4930. Korean      ko
  4931. Kurdish     ku
  4932. Laothian    lo
  4933. Latin       la
  4934. Latvian,    lv
  4935. Lettish
  4936. Lingala     ln
  4937. Lithuanian  lt
  4938. Macedonian  mk
  4939. Malagasy    mg
  4940. Malay       ms
  4941. Malayalam   ml
  4942. Maltese     mt
  4943. Maori       mi
  4944. Marathi     mr
  4945. Moldavian   mo
  4946. Mongolian   mn
  4947. Nauru       na
  4948. Nepali      ne
  4949. Norwegian   no
  4950. Occitan     oc
  4951. Oriya       or
  4952. Pashto, Pushto  ps
  4953. Persian     fa
  4954. Polish      pl
  4955. Portuguese  pt
  4956. Punjabi     pa
  4957. Quechua     qu
  4958. Rhaeto-Romance  rm
  4959. Romanian    ro
  4960. Russian     ru
  4961. Samoan      sm
  4962. Sangro      sg
  4963. Sanskrit    sa
  4964. Scots Gaelic    gd
  4965. Serbian     sr
  4966. Serbo-Croatian  sh
  4967. Sesotho     st
  4968. Setswana    tn
  4969. Shona       sn
  4970. Sindhi      sd
  4971. Singhalese  si
  4972. Siswati     ss
  4973. Slovak      sk
  4974. Slovenian   sl
  4975. Somali      so
  4976. Spanish     es
  4977. Sudanese    su
  4978. Swahili     sw
  4979. Swedish     sv
  4980. Tagalog     tl
  4981. Tajik       tg
  4982. Tamil       ta
  4983. Tatar       tt
  4984. Tegulu      te
  4985. Thai        th
  4986. Tibetan     bo
  4987. Tigrinya    ti
  4988. Tonga       to
  4989. Tsonga      ts
  4990. Turkish     tr
  4991. Turkmen     tk
  4992. Twi     tw
  4993. Uigur       ug
  4994. Ukrainian   uk
  4995. Urdu        ur
  4996. Uzbek       uz
  4997. Vietnamese  vi
  4998. Volapuk     vo
  4999. Welch       cy
  5000. Wolof       wo
  5001. Xhosa       xh
  5002. Yiddish     yi
  5003. (former ji)
  5004. Yoruba      yo
  5005. Zhuang      za
  5006. Zulu        zu
  5007. EOF
  5008. }
  5009.  
  5010.  
  5011.  
  5012. ##################################################
  5013. # Cut last n lines in file, 10 by default    #
  5014. ##################################################
  5015.  
  5016. function cuttail()
  5017. {
  5018.     nlines=${2:-10}
  5019.     sed -n -e :a -e "1,${nlines}!{P;N;D;};N;ba" $1
  5020. }
  5021.  
  5022.  
  5023.  
  5024. ##################################################
  5025. # Continuously print string as if being entered  #
  5026. # from the keyboard              #
  5027. ##################################################
  5028.  
  5029. function cycle() { while :;do((i++));echo -n "${3:$(($i%${#3})):1}";sleep .$(($RANDOM%$2+$1));done;}
  5030.  
  5031.  
  5032.  
  5033. ##################################################
  5034. # Super stealth background launch        #
  5035. ##################################################
  5036.  
  5037. function daemon()
  5038. {
  5039.     (exec "$@" >&/dev/null &)
  5040. }
  5041.  
  5042.  
  5043.  
  5044. ##################################################
  5045. # Shows what processes need to be restarted after#
  5046. # system upgrade                 #
  5047. ##################################################
  5048.  
  5049. function deadlib() { lsof | grep 'DEL.*lib' | cut -f 1 -d ' ' | sort -u; }
  5050.  
  5051.  
  5052.  
  5053. ##################################################
  5054. # Show dead links                #
  5055. ##################################################
  5056.  
  5057. function deadlink() {
  5058.     # copyright 2007 - 2010 Christopher Bratusek
  5059.     find -L -type l
  5060. }
  5061.  
  5062.  
  5063.  
  5064. ##################################################
  5065. # Deb Extraction / Remaker (extracts a deb   #
  5066. # file & organizes for easy deb manipulation     #
  5067. # and repacking using "debremaker")      #
  5068. ##################################################
  5069.  
  5070. function debextract()
  5071. {
  5072.     read -sn 1 -p "Press any key to continue...
  5073. "
  5074.     # Set IFS so that it won't consider spaces as entry separators.  Without this, spaces in file/folder names can make the loop go wacky.
  5075.     IFS=$'\n'
  5076.     NEWDIRNAME=${1%.*}
  5077.     FILENAME=${1##*/}
  5078.     NAME=${1##*/.*}
  5079.     mkdir "$NEWDIRNAME"
  5080.     cp -fv -R "$1" "$NEWDIRNAME"
  5081.     cd "$NEWDIRNAME"
  5082.     ar vx "$FILENAME"
  5083.     rm -fv -R "$FILENAME"
  5084.     for FILE in *.tar.gz; do tar xvpf $FILE; done
  5085.     for FILE in *.tar.lzma; do tar xvpf $FILE; done
  5086.     rm -fv -R "control.tar.gz"
  5087.     rm -fv -R "data.tar.gz"
  5088.     rm -fv -R "data.tar.lzma"
  5089.     rm -fv -R "debian-binary"
  5090.     mkdir "DEBIAN"
  5091.     mv -fv "changelog" "DEBIAN"
  5092.     mv -fv "config" "DEBIAN"
  5093.     mv -fv "conffiles" "DEBIAN"
  5094.     mv -fv "control" "DEBIAN"
  5095.     mv -fv "copyright" "DEBIAN"
  5096.     mv -fv "postinst" "DEBIAN"
  5097.     mv -fv "preinst" "DEBIAN"
  5098.     mv -fv "prerm" "DEBIAN"
  5099.     mv -fv "postrm" "DEBIAN"
  5100.     mv -fv "rules" "DEBIAN"
  5101.     mv -fv "shlibs" "DEBIAN"
  5102.     mv -fv "templates" "DEBIAN"
  5103.     mv -fv "triggers" "DEBIAN"
  5104.     mv -fv ".svn" "DEBIAN"
  5105.     rm -fv -R "md5sums"
  5106.     echo "Finished Successfully"
  5107. }
  5108.  
  5109.  
  5110.  
  5111. function debremaker()
  5112. {
  5113.     read -sn 1 -p "Make sure you have this function directed to the original debian file (previously extracted from and made into a folder with \"debextract\"; otherwise, it will fail (Note: This will take a minute): Press any key to continue...
  5114. "
  5115.     # Set IFS so that it won't consider spaces as entry separators.  Without this, spaces in file/folder names can make the loop go wacky.
  5116.     IFS=$'\n'
  5117.     NEWDIRNAME=${1%.*}
  5118.     FILENAME=${1##*/}
  5119.     NAME=${1##*/.*}
  5120.     cd "$NEWDIRNAME"
  5121.     rm -fv -R "$1"
  5122.     find . -type f ! -regex '.*\.hg.*' ! -regex '.*?debian-binary.*' ! -regex '.*?DEBIAN.*' -printf '%P ' | xargs md5sum > DEBIAN/md5sums
  5123.     cd ..
  5124.     dpkg-deb -b "$NEWDIRNAME"
  5125.     rm -rf "$NEWDIRNAME"
  5126.     echo "Finished Successfully"
  5127. }
  5128.  
  5129.  
  5130.  
  5131. ##################################################
  5132. # Download a web page and show info on what  #
  5133. # took time                  #
  5134. ##################################################
  5135.  
  5136. function debug_http() { /usr/bin/curl $@ -o /dev/null -w "dns: %{time_namelookup} connect: %{time_connect} pretransfer: %{time_pretransfer} starttransfer: %{time_starttransfer} total: %{time_total}\n" ; }
  5137.  
  5138.  
  5139.  
  5140. ##################################################
  5141. # Defragmentation of selected files/folder   #
  5142. # (use at your own risk) & fragmentation-checking#
  5143. ##################################################
  5144.  
  5145. function defrag()
  5146. {
  5147. cd "$1"
  5148. read -sn 1 -p "Warning! Pressing enter will defrag the current directory. Close this now if you are in the wrong directory and/or you forgot to type the name of the directory you wish to defrag after \"defrag\": Press any key to continue...
  5149. "
  5150. read -sn 1 -p "I'm serious. It's now or never...: Press any key to continue...
  5151. "
  5152. cat > "/tmp/defrag.sh" <<"End-of-message"
  5153. #!/bin/bash
  5154. # defrag v0.08 by Con Kolivas <kernel@kolivas.org
  5155. # Braindead fs-agnostic defrag to rewrite files in order largest to smallest
  5156. # Run this in the directory you want all the files and subdirectories to be
  5157. # reordered. It will only affect one partition. It works best when run twice.
  5158. # Are you really crazy enough to be using this? It might blow your data
  5159. # into tiny little useless chunks.
  5160. trap 'abort' 1 2 15
  5161. renice 19 $$ > /dev/null
  5162. function abort()
  5163. {
  5164.     echo -e "\nAborting"
  5165.     rm -f tmpfile dirlist
  5166.     exit 1
  5167. }
  5168. function fail()
  5169. {
  5170.     echo -e "\nFailed"
  5171.     abort
  5172. }
  5173. declare -i filesize=0
  5174. declare -i numfiles=0
  5175. # The maximum size of a file we can easily cache in ram
  5176. declare -i maxsize=$((`awk '/MemTotal/ {print $2}' /proc/meminfo`*1024))
  5177. (( maxsize-= `awk '/Mapped/ {print $2}' /proc/meminfo` ))
  5178. (( maxsize/= 2))
  5179. if [[ -a tmpfile || -a dirlist  ]] ; then
  5180.     echo dirlist or tmpfile exists
  5181.     exit 1
  5182. fi
  5183. # Sort in the following order:
  5184. # 1) Depth of directory
  5185. # 2) Size of directory descending
  5186. # 3) Filesize descending
  5187. # I made this crap up. It's completely unvalidated.
  5188. echo "Creating list of files..."
  5189. # stupid script to find max directory depth
  5190. find -xdev -type d -printf "%d\n" | sort -n | uniq > dirlist
  5191. # sort directories in descending size order
  5192. cat dirlist | while read d;
  5193. do
  5194.     find -xdev -type d -mindepth $d -maxdepth $d -printf "\"%p\"\n" | \
  5195.         xargs du -bS --max-depth=0 | \
  5196.         sort -k 1,1nr -k 2 |\
  5197.         cut -f2 >> tmpfile
  5198.     if (( $? )) ; then
  5199.         fail
  5200.     fi
  5201. done
  5202. rm -f dirlist
  5203. # sort files in descending size order
  5204. cat tmpfile | while read d;
  5205. do
  5206.     find "$d" -xdev -type f -maxdepth 1 -printf "%s\t%p\n" | \
  5207.         sort -k 1,1nr | \
  5208.         cut -f2 >> dirlist
  5209.     if (( $? )) ; then
  5210.         fail
  5211.     fi
  5212. done
  5213. rm -f tmpfile
  5214. numfiles=`wc -l dirlist | awk '{print $1}'`
  5215. echo -e "$numfiles files will be reordered\n"
  5216. # copy to temp file, check the file hasn't changed and then overwrite original
  5217. cat dirlist | while read i;
  5218. do
  5219.     (( --numfiles ))
  5220.     if [[ ! -f $i ]]; then
  5221.         continue
  5222.     fi
  5223.     # We could be this paranoid but it would slow it down 1000 times
  5224.     # if [[ `lsof -f -- "$i"` ]]; then
  5225.     #   echo -e "\n File $i open! Skipping"
  5226.     #   continue
  5227.     # fi
  5228.     filesize=`find "$i" -printf "%s"`
  5229.     # read the file first to cache it in ram if possible
  5230.     if (( filesize < maxsize ))
  5231.     then
  5232.         echo -e "\r $numfiles files left                                                            \c"
  5233.         cat "$i" > /dev/null
  5234.     else
  5235.         echo -e "\r $numfiles files left - Reordering large file sized $filesize ...                \c"
  5236.     fi
  5237.     datestamp=`find "$i" -printf "%s"`
  5238.     cp -a -f "$i" tmpfile
  5239.     if (( $? )) ; then
  5240.         fail
  5241.     fi
  5242.     # check the file hasn't been altered since we copied it
  5243.     if [[ `find "$i" -printf "%s"` != $datestamp ]] ; then
  5244.         continue
  5245.     fi
  5246.     mv -f tmpfile "$i"
  5247.     if (( $? )) ; then
  5248.         fail
  5249.     fi
  5250. done
  5251. echo -e "\nSucceeded"
  5252. rm -f dirlist
  5253. End-of-message
  5254. chmod +x "/tmp/defrag.sh"
  5255. sudo "/tmp/defrag.sh" "$1"
  5256. read -sn 1 -p "When you are finished, press any key to continue...
  5257. "
  5258. rm "/tmp/defrag.sh"
  5259. }
  5260.  
  5261.  
  5262.  
  5263. ###### if run this in your $HOME directory, you will have to change permissions back
  5264. function defrag2()
  5265. {
  5266. cd "$1"
  5267. read -sn 1 -p "Warning! Pressing enter will defrag the current directory. Close this now if you are in the wrong directory and/or you forgot to type the name of the directory you wish to defrag after \"defrag\": Press any key to continue...
  5268. "
  5269. read -sn 1 -p "I'm serious. It's now or never...: Press any key to continue...
  5270. "
  5271. cat > "/tmp/defrag2.sh" <<"End-of-message"
  5272. #!/bin/bash
  5273. # Creator:  private_lock
  5274. # Recursively descend in a folder-structure and recreate every folder on ascending, to ensure it is
  5275. # sorted (check with 'ls -lU'). This will defrag the FAT32 file-system but not touch the files.
  5276. # count some statistics
  5277. directories=0
  5278. invalid=0
  5279. unreadable=0
  5280. # the latest modification date of a file within the given directory
  5281. function getMaxDate {
  5282.     # read the output of ls (one file per line, sorted for descending modification time)
  5283.     ls -1t "$1" | while read line; do
  5284.         # "return value" is piped through standard out
  5285.         echo "-d $(stat -c %y "$1"/"$line")"
  5286.         # stop after first line
  5287.         return
  5288.     done
  5289. }
  5290. # expect a single directory as argument
  5291. function rewrite {
  5292.     # get canonical path
  5293.     local canonical="$(readlink -f "$1")"
  5294.     if [[ ! -d "$1" || -h "$1" ]]; then
  5295.         echo "Skipping symbolic link \"$1\" -> \"$canonical\"!"
  5296.         let invalid+=1
  5297.         return
  5298.     fi
  5299.     if [[ ! -d "$1" || -h "$1" ]]; then
  5300.         echo \"$canonical\" is not a valid directory!
  5301.         let invalid+=1
  5302.         return
  5303.     fi
  5304.     cd "$canonical"
  5305.     if [[ $? != 0 ]]; then
  5306.         echo Cannot change to directory \"$canonical\"! Skipping ...
  5307.         let unreadable+=1
  5308.         return
  5309.     fi
  5310.     echo $canonical
  5311.     let directories+=1
  5312.     local isEmpty=true
  5313.     # recursive descend
  5314.     for d in *; do
  5315.         if [[ -d "$d" ]]; then
  5316.             rewrite "$d"
  5317.         fi
  5318.         let isEmpty=false
  5319.     done
  5320.     # ascend to parent of canonical (But don't ascend blindly)
  5321.     cd "$canonical"/..
  5322.     if [[ $isEmpty == true ]]; then
  5323.         # no need to recreate an empty directory, as it's zero entries are always sorted
  5324.         return
  5325.     fi
  5326.     # check for an empty temporary directory-name
  5327.     local tempdir="$canonical".bak
  5328.     if [[ -e "$tempdir" ]]; then
  5329.         # echo $tempdir exits
  5330.         local counter=1
  5331.         while [[ -e "$tempdir$counter" ]]; do
  5332.             # echo ${tempdir}${counter} exits
  5333.             let counter+=1
  5334.         done
  5335.         tempdir="${tempdir}${counter}"
  5336.     fi
  5337.     # TODO check file-system boundaries (don't move across)
  5338.     # rename the current directory
  5339.     mv "$canonical" "$tempdir"
  5340.     # create a new directory
  5341.     mkdir "$canonical"
  5342.     # move all the content from the old to the new directory
  5343.     # The whole script is build around the side-effect of mv to sort the entries.
  5344.     mv "$tempdir"/* "$canonical"
  5345.     # check, that the old directory is really empty
  5346.     if [[ "$(ls -A "$tempdir")" ]]; then
  5347.         echo ERROR: "$tempdir" is not empty!
  5348.         exit -2
  5349.     fi
  5350.     # restore permissions
  5351.     chmod --reference="$tempdir" "$canonical"
  5352.     # delete the old directory
  5353.     rmdir "$tempdir"
  5354.     # update the timestamp of the new directory
  5355.     # start off with today
  5356.     local maxDate=$(date)
  5357.     # evaluate the latest modification time of a file within this directory
  5358.     # empty directories would be set to now
  5359.     touch "$(getMaxDate "$canonical")" "$canonical"
  5360. }
  5361. # check commandline for help option
  5362. for a in "$@"; do
  5363.     if [[ ${a} = "-?" || ${a} = "-h"  || ${a} = "--help" ]]; then
  5364.         echo -e "\nUsage: folderSort [-?|-h|--help] [directories]\n"
  5365.         exit -1
  5366.     fi
  5367. done
  5368. # start processing the directories
  5369. if [[ "$#" -eq 0 ]]; then
  5370.     # no commandline argument was given -> work on the current directory
  5371.     rewrite .
  5372. else
  5373.     for a in "$@"; do
  5374.         rewrite ${a}
  5375.     done
  5376. fi
  5377. echo Processed a total of $directories directories!
  5378. if [[ $invalid > 0 ]]; then
  5379.     echo Found $invalid invalid directories!
  5380. fi
  5381. if [[ $unreadable > 0 ]]; then
  5382.     echo Found $unreadable directories, that could not be changed into!
  5383. fi
  5384. exit $(($invalid + $unreadable))
  5385. End-of-message
  5386. chmod +x "/tmp/defrag2.sh"
  5387. sudo "/tmp/defrag2.sh" "$1"
  5388. read -sn 1 -p "When you are finished, press any key to continue...
  5389. "
  5390. rm "/tmp/defrag2.sh"
  5391. }
  5392.  
  5393.  
  5394.  
  5395. ###### fragmentation check (basic check, which will generate a percentage of fragmentation)
  5396. function fragcheck()
  5397. {
  5398. cd "$1"
  5399. read -sn 1 -p "Warning! Pressing enter will do a search for fragmentation in the current directory. Close this now if you are in the wrong directory and/or you forgot to type the name of the directory you wish to do a fragcheck after \"fragcheck\": Press any key to continue...
  5400. "
  5401. cat > "/tmp/fragcheck.pl" <<"End-of-message"
  5402. #!/usr/bin/perl -w
  5403. # Original creator: _droop_
  5404. # Updated by: as
  5405. # Updated again by: user11
  5406. # this script search for frag on a fs
  5407. use strict;
  5408. # number of files
  5409. my $files = 0;
  5410. # number of fragment
  5411. my $fragments = 0;
  5412. # number of fragmented files
  5413. my $fragfiles = 0;
  5414. my $verbose;
  5415. if ($ARGV[0] eq '-v') { shift @ARGV; $verbose++; }
  5416. open (REPORT, "find " . $ARGV[0] . " -xdev -type f -print0 | xargs -0 filefrag |");
  5417. while (defined (my $res = <REPORT>)) {
  5418.         if ($res =~ m/.*:\s+(\d+) extents? found$/) {
  5419.                 my $fragment = $1;
  5420.                 $fragments += $fragment;
  5421.                 if ($fragment > 1) {
  5422.                         $fragfiles++;
  5423.                 }
  5424.                 $files++;
  5425.         } else {
  5426.                 print ("Failed to parse: $res\n");
  5427.         }
  5428. }
  5429. close (REPORT);
  5430. if ($verbose) {
  5431.    print "Total files:      $files\n";
  5432.    print "Fragmented files: $fragfiles\n";
  5433.    print "Fragments:        $fragments\n";
  5434. }
  5435. sub round($$) {
  5436.    my $v = shift; # value
  5437.    my $p = shift; # rouding divisor (1 for '123', 10 for '123.4', 100 for '123.45')
  5438.    return int($v * $p) / $p;
  5439. }
  5440. print ( $fragfiles / $files * 100 . "% non contiguous files, " . $fragments / $files . " average fragments.\n");
  5441. End-of-message
  5442. chmod +x "/tmp/fragcheck.pl"
  5443. sudo "/tmp/fragcheck.pl" "$1"
  5444. read -sn 1 -p "When you are finished, press any key to continue...
  5445. "
  5446. rm "/tmp/fragcheck.pl"
  5447. }
  5448.  
  5449.  
  5450.  
  5451. ###### will generate a percentage for fragmentation and several other things: takes longer than first one
  5452. function fragcheck2()
  5453. {
  5454. cd "$1"
  5455. read -sn 1 -p "Warning! Pressing enter will do a search for fragmentation in the current directory. Close this now if you are in the wrong directory and/or you forgot to type the name of the directory you wish to do a fragcheck after \"fragcheck\": Press any key to continue...
  5456. "
  5457. cat > "/tmp/fragcheck2.pl" <<"End-of-message"
  5458. #! /usr/bin/perl -w
  5459. #  Original creator: _droop_
  5460. #  Updated by: as
  5461. #  Updated again by: c07
  5462. use strict;
  5463. @ARGV >= 1 && @ARGV <= 2 or die "usage: $0 <dir> [<block size in KB>]";
  5464. $/= "\0";
  5465. my ($files, $blocks, $fragments, $frag, $fragblocks, $multi, $empty)= (0) x 7;
  5466. my $dir= shift;
  5467. my $blocksize= (shift || 4) + 0;
  5468. print qq|scanning "$dir", using block size $blocksize KB ...\n|;
  5469. open my $find, "-|", "find", $dir, qw"-xdev -type f -print0";
  5470. while ( my $file= <$find> ) {
  5471.   { open my $fh, "-|", "filefrag", $file; $_= <$fh> }
  5472.   /:\s+(\d+) extents? found/ or (print qq|"$_"?\n|), next;
  5473.   my $n= $1 + 0;
  5474.   { open my $fh, "-|", "ls", "-sk", $file; $_= <$fh> }
  5475.   /^(\d+)\s/ or (print qq|"$_" (ls)?\n|), next;
  5476.   my $s= $1 / $blocksize;
  5477.   ++$files;
  5478.   $s or ++$empty, next;
  5479.   $blocks += $s;
  5480.   $fragments += $n;
  5481.   ++$frag, $fragblocks += $s if $n > 1;
  5482.   ++$multi if $s > 1;
  5483. }
  5484. my $single= $files - $multi - $empty;
  5485. my $nonfrag= $files - $frag - $empty;
  5486. if ( ! $files ) { print "no files\n" }
  5487. else {
  5488.   printf "$files files, $frag (%.3f %%) fragmented\n", 100 * $frag / $files;
  5489.   if ( ! $multi ) { print "no multi-block files\n" }
  5490.   else {
  5491.     printf "$multi multi-block files, %.3f %% fragmented\n",
  5492.       100 * $frag / $multi;
  5493.   }
  5494.   print "$blocks blocks, $fragments fragments, $empty empty files\n";
  5495.   if ( $fragments ) {
  5496.     printf "average %.3f fragments per file, %.3f blocks per fragment,\n",
  5497.       $fragments / $files, $blocks / $fragments;
  5498.     if ( $multi ) {
  5499.       printf "%.3f fragments per multi-block file, %.3f blocks each,\n",
  5500.         ($fragments - $single) / $multi,
  5501.         ($blocks - $single) / ($fragments - $single);
  5502.       if ( $frag ) {
  5503.         printf "%.3f fragments per fragmented file, %.3f blocks each\n",
  5504.         ($fragments - $nonfrag) / $frag,
  5505.         $fragblocks / ($fragments - $nonfrag);
  5506. } } } }
  5507. End-of-message
  5508. chmod +x "/tmp/fragcheck2.pl"
  5509. sudo "/tmp/fragcheck2.pl" "$1"
  5510. read -sn 1 -p "When you are finished, press any key to continue...
  5511. "
  5512. rm "/tmp/fragcheck2.pl"
  5513. }
  5514.  
  5515.  
  5516.  
  5517. ##################################################
  5518. # Delete function                #
  5519. ##################################################
  5520.  
  5521. function del()
  5522. {
  5523.     mv "$@" "/${HOME}/.local/share/Trash/files/"
  5524. }
  5525.  
  5526.  
  5527.  
  5528. function delete() {
  5529.     DIR=$1
  5530.     shift
  5531.     for i in $*; do
  5532.         if [ -f $DIR/$i ]; then
  5533.             rm $DIR/$i
  5534.         fi
  5535.     done
  5536. }
  5537.  
  5538.  
  5539.  
  5540. ##################################################
  5541. # Lookup a word with dict.org            #
  5542. ##################################################
  5543.  
  5544. ###### define "whatever"
  5545. function dic() { curl dict://dict.org/d:"$@" ; }
  5546.  
  5547.  
  5548.  
  5549. ###### find matches of $1, with optional strat $2 and optional db $3
  5550. function ref()
  5551. {
  5552.     if [[ -z $3 ]]; then
  5553.         curl dict://dict.org/m:${1}:english:${2};
  5554.     else
  5555.         curl dict://dict.org/m:${1}:${3}:${2};
  5556.     fi
  5557. }
  5558.  
  5559.  
  5560.  
  5561. ###### look in Webster
  5562. function webster() { curl dict://dict.org/d:${1}:web1913; }
  5563.  
  5564.  
  5565.  
  5566. ###### look in WordNet
  5567. function wordnet() { curl dict://dict.org/d:${1}:wn; }
  5568.  
  5569.  
  5570.  
  5571. ##################################################
  5572. # Shell function to exit script with error in    #
  5573. # exit status and print optional message to      #
  5574. # stderr                     #
  5575. ##################################################
  5576.  
  5577. function die() { result=$1;shift;[ -n "$*" ]&&printf "%s\n" "$*" >&2;exit $result;}
  5578.  
  5579.  
  5580.  
  5581. ##################################################
  5582. # Dirsize - finds directory sizes and lists  #
  5583. # them for the current directory         #
  5584. ##################################################
  5585.  
  5586. function dirsize()
  5587. {
  5588. du -shx * .[a-zA-Z0-9_]* 2> /dev/null | \
  5589. egrep '^ *[0-9.]*[MG]' | sort -n > /tmp/list
  5590. egrep '^ *[0-9.]*M' /tmp/list
  5591. egrep '^ *[0-9.]*G' /tmp/list
  5592. rm /tmp/list
  5593. }
  5594.  
  5595.  
  5596.  
  5597. ##################################################
  5598. # Display off (Turns the display off)        #
  5599. ##################################################
  5600.  
  5601. function display-off()
  5602. {
  5603. cat > "/tmp/display-off.py" <<"End-of-message"
  5604. #!/usr/bin/python
  5605. import time
  5606. import subprocess
  5607. from Xlib import X
  5608. from Xlib.display import Display
  5609. display = Display(':0')
  5610. root = display.screen().root
  5611. root.grab_pointer(True,
  5612.         X.ButtonPressMask | X.ButtonReleaseMask | X.PointerMotionMask,
  5613.         X.GrabModeAsync, X.GrabModeAsync, 0, 0, X.CurrentTime)
  5614. root.grab_keyboard(True,
  5615.         X.GrabModeAsync, X.GrabModeAsync, X.CurrentTime)
  5616. subprocess.call('xset dpms force off'.split())
  5617. p = subprocess.Popen('gnome-screensaver-command -i'.split())
  5618. time.sleep(1)
  5619. while True:
  5620.     print display.next_event()
  5621.     p.terminate()
  5622.     break
  5623. End-of-message
  5624. chmod +x "/tmp/display-off.py"
  5625. "/tmp/display-off.py"
  5626. rm "/tmp/display-off.py"
  5627. }
  5628.  
  5629.  
  5630.  
  5631. ###### Display off with login (Turns the display off)
  5632. function display-oft()
  5633. {
  5634. cat > "/tmp/display-oft.py" <<"End-of-message"
  5635. #!/usr/bin/python
  5636. import time
  5637. import subprocess
  5638. from Xlib import X
  5639. from Xlib.display import Display
  5640. display = Display(':0')
  5641. root = display.screen().root
  5642. root.grab_pointer(True,
  5643.         X.ButtonPressMask | X.ButtonReleaseMask | X.PointerMotionMask,
  5644.         X.GrabModeAsync, X.GrabModeAsync, 0, 0, X.CurrentTime)
  5645. root.grab_keyboard(True,
  5646.         X.GrabModeAsync, X.GrabModeAsync, X.CurrentTime)
  5647. subprocess.call('xset dpms force off'.split())
  5648. p = subprocess.Popen('gnome-screensaver-command -i'.split())
  5649. time.sleep(1)
  5650. while True:
  5651.     print display.next_event()
  5652.     p.terminate()
  5653.     subprocess.Popen('gnome-screensaver-command -l'.split())
  5654.     break
  5655. End-of-message
  5656. chmod +x "/tmp/display-oft.py"
  5657. "/tmp/display-oft.py"
  5658. rm "/tmp/display-oft.py"
  5659. }
  5660.  
  5661.  
  5662.  
  5663. ##################################################
  5664. # Change to specified pkg's documentation dir and#
  5665. # display the files              #
  5666. ##################################################
  5667.  
  5668. ###### Usage: doc
  5669. function doc() {
  5670.     pushd "/usr/share/doc/$1" && ls
  5671. }
  5672.  
  5673.  
  5674.  
  5675. ##################################################
  5676. # Lists unique IPs currently connected to    #
  5677. # logged-in system & how many concurrent     #
  5678. # connections each IP has            #
  5679. ##################################################
  5680.  
  5681. function doscheck()
  5682. {
  5683. "netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n"
  5684. }
  5685.  
  5686.  
  5687.  
  5688. ##################################################
  5689. # Symlinks all hidden files in a directory to the#
  5690. # same names without the dot             #
  5691. ##################################################
  5692.  
  5693. function dot_ln()
  5694. {
  5695.     for file in `/bin/ls -a | /bin/egrep "^\.[^./]"` ; do
  5696.         if [[ "$1" == "-f" ]] ; then
  5697.             /bin/ln -svif $file ${file:1}
  5698.         else
  5699.             /bin/ln -svi $file ${file:1}
  5700.         fi
  5701.     done
  5702. }
  5703.  
  5704.  
  5705.  
  5706. ##################################################
  5707. # Site down for everyone or just me?         #
  5708. ##################################################
  5709.  
  5710. function downforme() {
  5711.     RED='\e[1;31m'
  5712.     GREEN='\e[1;32m'
  5713.     YELLOW='\e[1;33m'
  5714.     NC='\e[0m'
  5715.     if [ $# = 0 ]
  5716.     then
  5717.         echo -e "${YELLOW}usage:${NC} downforme website_url"
  5718.     else
  5719.         JUSTYOUARRAY=(`lynx -dump http://downforeveryoneorjustme.com/$1 | grep -o "It's just you"`)
  5720.         if [ ${#JUSTYOUARRAY} != 0 ]
  5721.         then
  5722.             echo -e "${RED}It's just you. \n${NC}$1 is up."
  5723.         else
  5724.             echo -e "${GREEN}It's not just you! \n${NC}$1 looks down from here."
  5725.         fi
  5726.     fi
  5727. }
  5728.  
  5729.  
  5730.  
  5731. ##################################################
  5732. # Size of directories in MB          #
  5733. ##################################################
  5734.  
  5735. function ds()
  5736. {
  5737.     echo "size of directories in MB"
  5738.     if [ $# -lt 1 ] || [ $# -gt 2 ]; then
  5739.         echo "you did not specify a directy, using pwd"
  5740.         DIR=$(pwd)
  5741.         find $DIR -maxdepth 1 -type d -exec du -sm \{\} \; | sort -nr
  5742.     else
  5743.         find $1 -maxdepth 1 -type d -exec du -sm \{\} \; | sort -nr
  5744.     fi
  5745. }
  5746.  
  5747.  
  5748.  
  5749. ##################################################
  5750. # Size of items in directory             #
  5751. ##################################################
  5752.  
  5753. function dubigf() {
  5754.   du -sh * | awk '/[[:space:]]*[[:digit:]]+,*[[:digit:]]*G/' | sort -nr
  5755.   du -sh * | awk '/[[:space:]]*[[:digit:]]+,*[[:digit:]]*M/' | sort -nr
  5756. }
  5757.  
  5758.  
  5759.  
  5760. ##################################################
  5761. # View portage changelog for specified package   #
  5762. ##################################################
  5763.  
  5764. ######   $1 = package name
  5765. function echange() {
  5766.     PACKAGE="$(eix -e --only-names $1)"
  5767.     if [ "$PACKAGE" != "" ]; then
  5768.         view /usr/portage/$PACKAGE/ChangeLog
  5769.     fi
  5770. }
  5771.  
  5772.  
  5773.  
  5774. ##################################################
  5775. # Directory operations: editd, flipd, popd,      #
  5776. # printd, pushd, rotd, swapd             #
  5777. ##################################################
  5778.  
  5779. ###### Edit directory stack
  5780. function editd() {
  5781.   export EDITDNO=$((${EDITDNO:=0} + 1))
  5782.   typeset FiLe=/tmp/`basename -- $0`$$.${EDITDNO}
  5783.   printd >${FiLe}
  5784.   ${EDITOR} ${FiLe}
  5785.   DS=`while read ea; do echo -n "$ea:"; done <${FiLe}`
  5786.   rm -f ${FiLe}
  5787. }
  5788.  
  5789.  
  5790.  
  5791. ###### flip back-and-forth between current dir and top of stack (like "cd -")
  5792. function flipd() {
  5793.   if [ "$DS" ]
  5794.   then
  5795.     cd "${DS%%:*}"
  5796.     export DS="$OLDPWD:${DS#*:}"
  5797.   else
  5798.     echo "$0: empty directory stack" >&2
  5799.   fi
  5800. }
  5801.  
  5802.  
  5803.  
  5804. ###### pop top dir off stack and cd to it
  5805. function popd() {
  5806.   if [ "$DS" ]
  5807.   then
  5808.     cd "${DS%%:*}"
  5809.     export DS="${DS#*:}"
  5810.   else
  5811.     echo "$0: empty directory stack" >&2
  5812.   fi
  5813. }
  5814.  
  5815.  
  5816.  
  5817. ###### Print directory stack
  5818. function printd() {
  5819.   ( IFS=:; for each in $DS; do echo $each; done; )
  5820. }
  5821.  
  5822.  
  5823.  
  5824. ###### Change to new dir, pushing current onto stack
  5825. function pushd() {
  5826.   export DS="$PWD:$DS"
  5827.   if [ -n "$1" ]; then cd "$1"; else cd; fi || export DS="${DS#*:}"
  5828. }
  5829.  
  5830.  
  5831.  
  5832. ###### rotate thru directory stack (from bottom to top)
  5833. function rotd() {
  5834.   if [ "$DS" ]
  5835.   then
  5836.     typeset DSr="${DS%:*:}"
  5837.     [ "${DSr}" = "${DS}" ] || export DS="${DS##${DSr}:}$DSr:"
  5838.     flipd
  5839.   else
  5840.     echo "$0: directory stack is empty" >&2
  5841.   fi
  5842. }
  5843.  
  5844.  
  5845.  
  5846. ###### swap top two dir stack entries
  5847. function swapd() {
  5848.   typeset DSr="${DS#*:}"
  5849.   if [ "$DSr" ]
  5850.   then
  5851.     export DS="${DSr%%:*}:${DS%%:*}:${DSr#*:}"
  5852.   else
  5853.     echo "$0: less than two on directory stack" >&2
  5854.   fi
  5855. }
  5856.  
  5857.  
  5858.  
  5859. if [ ! -f ${HOME}/.lastdir ];then
  5860.     cat > ${HOME}/.lastdir
  5861. fi
  5862.  
  5863.  
  5864.  
  5865. alias lastd="cd $(cat ~/.lastdir)"         # change to last dir at 'bye'
  5866.  
  5867.  
  5868.  
  5869. ###### save current dir for lastd on exit if not $HOME
  5870. alias saved='[ ${PWD} != ${HOME} ] && pwd >~/.lastdir; [ -n "${DS}" ] && echo "${DS}" >~/.dirstak'
  5871.  
  5872.  
  5873.  
  5874. ###### get dir stack back on login
  5875. [ -s ${HOME}/.dirstak ] && export DS=`cat ${HOME}/.dirstak`
  5876.  
  5877.  
  5878.  
  5879. ##################################################
  5880. # Edit the svn log at  the given revision    #
  5881. ##################################################
  5882.  
  5883. function editsvnlog() {
  5884.     svn propedit svn:log --revprop -r$1 --editor-cmd gedit
  5885. }
  5886.  
  5887.  
  5888.  
  5889. ##################################################
  5890. # Download ed2k file                 #
  5891. ##################################################
  5892.  
  5893. function ed2k()
  5894. {
  5895. wget -q -O - "$1" | grep "ed2k://" |  sed -e 's/^.*=//g;s/..$//g'
  5896. }
  5897.  
  5898.  
  5899.  
  5900. ##################################################
  5901. # Elements database              #
  5902. ##################################################
  5903.  
  5904. function ele() {
  5905.     dict -d elements $@
  5906. }
  5907.  
  5908.  
  5909.  
  5910. ##################################################
  5911. # Show empty files in the directed directory     #
  5912. ##################################################
  5913.  
  5914. function empty() {
  5915.     # copyright 2007 - 2010 Christopher Bratusek
  5916.     find "$1" -empty
  5917. }
  5918.  
  5919.  
  5920.  
  5921. ##################################################
  5922. # Surround lines with quotes (useful in pipes)   #
  5923. # - from mervTormel              #
  5924. ##################################################
  5925.  
  5926. function enquote() { /usr/bin/sed 's/^/"/;s/$/"/' ; }
  5927.  
  5928.  
  5929.  
  5930. ##################################################
  5931. # Determining the meaning of error codes     #
  5932. ##################################################
  5933.  
  5934. function err()
  5935. {
  5936.     grep --recursive --color=auto --recursive -- "$@" /usr/include/*/errno.h
  5937.     if [ "${?}" != 0 ]; then
  5938.         echo "Not found."
  5939.     fi
  5940. }
  5941.  
  5942.  
  5943.  
  5944. ##################################################
  5945. # View latest installable portage ebuild for     #
  5946. # specified package              #
  5947. ##################################################
  5948.  
  5949. ######   $1 = package name
  5950. function eview() {
  5951.     FILE=$(equery which $1)
  5952.     if [ -f "$FILE" ]; then
  5953.         view $FILE
  5954.     fi
  5955. }
  5956.  
  5957.  
  5958.  
  5959. ##################################################
  5960. # Exchange stuff from two places         #
  5961. ##################################################
  5962.  
  5963. function exchange()
  5964. # copyright 2007 - 2010 Christopher Bratusek
  5965. {
  5966.     typeset temp
  5967.     SAVE=$IFS
  5968.     IFS=''
  5969.     eval $(echo "temp=\"\$$1\"")
  5970.     eval $(echo "$1=\"\$$2\"")
  5971.     eval $(echo "$2=\"$temp\"")
  5972.     IFS=$SAVE
  5973. }
  5974.  
  5975.  
  5976.  
  5977. ##################################################
  5978. # Extract - extract most common compression  #
  5979. # types                      #
  5980. ##################################################
  5981.  
  5982. function extract() {
  5983.   local e=0 i c
  5984.   for i; do
  5985.     if [[ -f $i && -r $i ]]; then
  5986.         c=''
  5987.         case $i in
  5988.           *.t@(gz|lz|xz|b@(2|z?(2))|a@(z|r?(.@(Z|bz?(2)|gz|lzma|xz)))))
  5989.                  c='bsdtar xvf' ;;
  5990.           *.7z)  c='7z x'       ;;
  5991.           *.Z)   c='uncompress' ;;
  5992.           *.bz2) c='bunzip2'    ;;
  5993.           *.exe) c='cabextract' ;;
  5994.           *.gz)  c='gunzip'     ;;
  5995.           *.rar) c='unrar x'    ;;
  5996.           *.xz)  c='unxz'       ;;
  5997.           *.zip) c='unzip'      ;;
  5998.           *)     echo "$0: cannot extract \`$i': Unrecognized file extension" >&2; e=1 ;;
  5999.        esac
  6000.        [[ $c ]] && command $c "$i"
  6001.    else
  6002.        echo "$0: cannot extract \`$i': File is unreadable" >&2; e=2
  6003.     fi
  6004.   done
  6005.   return $e
  6006. }
  6007.  
  6008.  
  6009.  
  6010. ##################################################
  6011. # CIA world fact book                #
  6012. ##################################################
  6013.  
  6014. function fact() {
  6015.     dict -d world02 $@
  6016. }
  6017.  
  6018.  
  6019.  
  6020. ##################################################
  6021. # Passwording                    #
  6022. ##################################################
  6023.  
  6024. ###### fake name and pass
  6025. function fakepass()
  6026. {
  6027.   local l=8
  6028.   [ -n "$1" ] && l=$1
  6029.   dd if=/dev/urandom count=1 2> /dev/null | uuencode -m - | head -n 2 | tail -n 1 | cut -c $l
  6030. }
  6031.  
  6032.  
  6033.  
  6034. alias fakename='nc koeln.ccc.de 23 | cut -d \  -f 4,5'
  6035.  
  6036.  
  6037.  
  6038. ###### password file
  6039. function pw()
  6040. {
  6041.     if [ "$OS" = "Linux" ]; then
  6042.         gpg $HOME/priv.asc
  6043.         vi -n $HOME/priv
  6044.         gpg -ea $HOME/priv
  6045.         wipe -f $HOME/priv
  6046.     elif [ "$OS" = "Darwin" ]; then
  6047.         gpg $HOME/Documents/priv.asc
  6048.         vi -n $HOME/Documents/priv
  6049.         gpg -ea $HOME/Documents/priv
  6050.         srm -f $HOME/Documents/priv
  6051.     fi
  6052. }
  6053.  
  6054.  
  6055.  
  6056. ###### generate a random password
  6057. #   $1 = number of characters; defaults to 32
  6058. #   $2 = include special characters; 1 = yes, 0 = no; defaults to 1
  6059. # copyright 2007 - 2010 Christopher Bratusek
  6060. function randompw() {
  6061.     if [[ $2 == "!" ]]; then
  6062.         echo $(cat /dev/urandom | tr -cd '[:graph:]' | head -c ${1:-32})
  6063.     else    echo $(cat /dev/urandom | tr -cd '[:alnum:]' | head -c ${1:-32})
  6064.     fi
  6065. }
  6066.  
  6067.  
  6068.  
  6069. ###### generate a random left-hand password
  6070. alias randompwl='</dev/urandom tr -dc '12345!@#$%qwertQWERTasdfgASDFGzxcvbZXCVB' | head -c8; echo ""'
  6071.  
  6072.  
  6073.  
  6074. ###### generate a unique and secure password for every website that you login to
  6075. function sitepass() { echo -n "$@" |  md5sum | sha1sum | sha224sum | sha256sum | sha384sum | sha512sum | gzip - | strings -n 1 | tr -d "[:space:]"  | tr -s '[:print:]' | tr '!-~' 'P-~!-O' | rev | cut -b 2-11; history -d $(($HISTCMD-1)); }
  6076.  
  6077.  
  6078.  
  6079. ###### generates a unique and secure password with SALT for every website that you login to
  6080. function sitepass2()
  6081. {
  6082. salt="this_salt";pass=`echo -n "$@"`;for i in {1..500};do pass=`echo -n $pass$salt|sha512sum`;done;echo$pass|gzip -|strings -n 1|tr -d "[:space:]"|tr -s '[:print:]' |tr '!-~' 'P-~!-O'|rev|cut -b 2-15;history -d $(($HISTCMD-1));
  6083. }
  6084.  
  6085.  
  6086.  
  6087. ###### trunc    password
  6088. function trunc_pwd()
  6089. # copyright 2007 - 2010 Christopher Bratusek
  6090. {
  6091.     case $1 in
  6092.         *help )
  6093.             echo -e "\n${ewhite}Usage:\n"
  6094.             echo -e "${eorange}trunc_pwd ${ewhite}|${egreen} ! no options !\n"
  6095.             tput sgr0
  6096.         ;;
  6097.         * )
  6098.             pwdmaxlen=$(get_key pwdmaxlength)
  6099.             trunc_symbol=$(get_key pwdchar)
  6100.             dirchar=$(get_key dirchar)
  6101.             newsepacolor=$(echo $sepacolor | sed -e 's/\\\[//g' -e 's/\\\]//g')
  6102.             newwdircolor=$(echo $wdircolor | sed -e 's/\\\[//g' -e 's/\\\]//g')
  6103.             newpscoloror=$(echo $pscolor | sed -e 's/\\\[//g' -e 's/\\\]//g')
  6104.             if [ ${#PWD} -gt $pwdmaxlen ]; then
  6105.                 pwdoffset=$(( ${#PWD} - $pwdmaxlen ))
  6106.                 if [[ $pstyle_supported == true ]]; then
  6107.                     xPWD="$newpscoloror${trunc_symbol}${PWD:$pwdoffset:$pwdmaxlen}"
  6108.                 else    xPWD="${trunc_symbol}${PWD:$pwdoffset:$pwdmaxlen}"
  6109.                 fi
  6110.                 if [[ $enabcol == true && $pstyle_supported == true ]]; then
  6111.                     newPWD="${xPWD//\//$newsepacolor$dirchar$newwdircolor}"
  6112.                 else    newPWD="${xPWD//\//$dirchar}"
  6113.                 fi
  6114.             else
  6115.                 if [[ $enabcol == true && $pstyle_supported == true ]]; then
  6116.                 newPWD="${PWD//\//$newsepacolor$dirchar$newwdircolor}"
  6117.             else    newPWD="${PWD//\//$dirchar}"
  6118.             fi
  6119.             fi
  6120.             echo -e $newPWD
  6121.         ;;
  6122.     esac
  6123. }
  6124.  
  6125.  
  6126.  
  6127. ##################################################
  6128. # Find a file(s) ...                 #
  6129. ##################################################
  6130.  
  6131. ###### ... with pattern $1 in name and Execute $2 on it
  6132. function fe() { find . -type f -iname '*'$1'*' -exec "${2:-file}" {} \;  ; }
  6133.  
  6134.  
  6135.  
  6136. ###### ... under the current directory
  6137. function ff() { /usr/bin/find . -name "$@" ; }
  6138.  
  6139.  
  6140.  
  6141. ###### ... whose name ends with a given string
  6142. function ffe() { /usr/bin/find . -name '*'"$@" ; }
  6143.  
  6144.  
  6145.  
  6146. ###### ... whose name starts with a given string
  6147. function ffs() { /usr/bin/find . -name "$@"'*' ; }
  6148.  
  6149.  
  6150.  
  6151. ###### ... larger than a certain size (in bytes)
  6152. function find_larger() { find . -type f -size +${1}c ; }
  6153.  
  6154.  
  6155.  
  6156. ###### find a file with a pattern in name in the local directory
  6157. function fp()
  6158. {
  6159.     find . -type f -iname '*'$*'*' -ls ;
  6160. }
  6161.  
  6162.  
  6163.  
  6164. ###### find pattern in a set of files and highlight them
  6165. function fstr()
  6166. {
  6167.     OPTIND=1
  6168.     local case=""
  6169.     local usage="fstr: find string in files.
  6170. Usage: fstr [-i] \"pattern\" [\"filename pattern\"] "
  6171.     while getopts :it opt
  6172.     do
  6173.         case "$opt" in
  6174.         i) case="-i " ;;
  6175.         *) echo "$usage"; return;;
  6176.         esac
  6177.     done
  6178.     shift $(( $OPTIND - 1 ))
  6179.     if [ "$#" -lt 1 ]; then
  6180.         echo "$usage"
  6181.         return;
  6182.     fi
  6183.     local SMSO=$(tput smso)
  6184.     local RMSO=$(tput rmso)
  6185.     find . -type f -name "${2:-*}" -print0 | xargs -0 grep -sn ${case} "$1" 2>&- | \
  6186. sed "s/$1/${SMSO}\0${RMSO}/gI" | more
  6187. }
  6188.  
  6189.  
  6190.  
  6191. ###### searches through the text of all the files in your current directory
  6192. # http://seanp2k.com/?p=13
  6193. # Good for debugging a PHP script you didn't write and can't trackdown where MySQL connect string actually is
  6194. # function grip() {
  6195. # grep -ir "$1″ "$PWD"
  6196. # }
  6197.  
  6198.  
  6199.  
  6200. ###### ... who is the newest file in a directory
  6201. function newest() { find ${1:-\.} -type f |xargs ls -lrt ; }
  6202.  
  6203.  
  6204.  
  6205. ##################################################
  6206. # Festival - text-to-speech              #
  6207. ##################################################
  6208.  
  6209. ###### requires festival: sudo apt-get install festival
  6210. # Usage:    fest "text"
  6211. function fest() {
  6212.     echo $1 | festival --tts
  6213. }
  6214.  
  6215.  
  6216.  
  6217. ##################################################
  6218. # Find in file and ( AND relation )      #
  6219. ##################################################
  6220.  
  6221. # Will search PWD for text files that contain $1 AND $2 AND $3 etc...
  6222. # Actually it does the same as grep word1|grep word2|grep word3 etc, but in a more elegant way.
  6223. function ffa() { (($# < 2)) && { echo "usage: ffa pat1 pat2 [...]" >&2; return 1; };awk "/$1/$(printf "&&/%s/" "${@:2}")"'{ print FILENAME ":" $0 }' *; }
  6224.  
  6225.  
  6226.  
  6227. ##################################################
  6228. # Pick the first program found from a list of    #
  6229. # alternatives                   #
  6230. ##################################################
  6231.  
  6232. ###### used to set environmental variables from list of alternatives depending on what's installed (uses bash setting 'export BROWSER' above)
  6233. # it returns the first program found in the list
  6234. # Usage:    export BROWSER=$(find_alternatives chromium-browser google-chrome opera firefox firefox-bin iceweasel konqueror w3m lynx)
  6235. function find_alternatives() { for i;do which "$i" >/dev/null && { echo "$i"; return 0;};done;return 1; }
  6236.  
  6237.  
  6238.  
  6239. ##################################################
  6240. # Find out the pid of a specified process    #
  6241. ##################################################
  6242.  
  6243. ######  note that the command name can be specified via a regex
  6244. #    E.g. findPid '/d$/' finds pids of all processes with names ending in 'd'
  6245. #    Without the 'sudo' it will only find processes of the current user
  6246. function findPid() { sudo /usr/sbin/lsof -t -c "$@" ; }
  6247.  
  6248.  
  6249.  
  6250. ##################################################
  6251. # Search for a word in the Unix word list    #
  6252. ##################################################
  6253.  
  6254. function findword() { /usr/bin/grep ^"$@"$ /usr/share/dict/words ; }
  6255.  
  6256.  
  6257.  
  6258. ##################################################
  6259. # Recursively fix dir/file permissions on a  #
  6260. # given directory                #
  6261. ##################################################
  6262.  
  6263. function fix() {
  6264. if [ -d $1 ]; then
  6265. find $1 -type d -exec chmod 755 {} \;
  6266. find $1 -type f -exec chmod 644 {} \;
  6267. else
  6268. echo "$1 is not a directory."
  6269. fi
  6270. }
  6271.  
  6272.  
  6273.  
  6274. ##################################################
  6275. # Edit files in place to ensure Unix line-   #
  6276. # endings                    #
  6277. ##################################################
  6278.  
  6279. function fixlines() { /usr/bin/perl -pi~ -e 's/\r\n?/\n/g' "$@" ; }
  6280.  
  6281.  
  6282.  
  6283. ##################################################
  6284. # Inserts a flag with the specified content  #
  6285. ##################################################
  6286.  
  6287. ###### Usage: flag "comment"
  6288. # If no comment, inserts the date.
  6289. function flag() {
  6290.     if [ "$1" == "" ];
  6291.     then
  6292.         echo -e  "\e[0;31m[====== " `date +"%A %e %B %Y"`, `date +"%H"`h`date +"%M"` " ======]\e[0m"
  6293.     else
  6294.         echo -e  "\e[0;31m[====== " $@ " ======]\e[0m"
  6295.     fi
  6296. }
  6297.  
  6298.  
  6299.  
  6300. ##################################################
  6301. # Inserts a flag and executes the command    #
  6302. ##################################################
  6303.  
  6304. ###### Example: flagcommand ls
  6305. function flagcommand() {
  6306.     if [ "$1" == "" ];
  6307.     then
  6308.         return
  6309.     else
  6310.         flag $@
  6311.         $@
  6312.     fi
  6313. }
  6314.  
  6315.  
  6316.  
  6317. ##################################################
  6318. # Flight status                  #
  6319. ##################################################
  6320.  
  6321. ###### track flights from the command line (requires html2text: sudo apt-get install html2text)
  6322. function flight_status() { if [[ $# -eq 3 ]];then offset=$3; else offset=0; fi; curl "http://mobile.flightview.com/TrackByRoute.aspx?view=detail&al="$1"&fn="$2"&dpdat=$(date +%Y%m%d -d ${offset}day)" 2>/dev/null |html2text |grep ":"; }
  6323.  
  6324.  
  6325.  
  6326. ##################################################
  6327. # Autofocus window after executing some command` #
  6328. ##################################################
  6329.  
  6330. ###### example: focus make all
  6331. # from: http://noisy-coder.blogspot.com/2010/10/autofocus-window.html
  6332. function focus() { winID=`xprop -root |awk '/_NET_ACTIVE_WINDOW/ {print $5; exit;}'`; $@; wmctrl -i -a $winID; }
  6333.  
  6334.  
  6335.  
  6336. ##################################################
  6337. # Weather and stuff              #
  6338. ##################################################
  6339.  
  6340. ###### 10-day forcast
  6341. # USAGE:    forecast 50315
  6342. function forecast() {
  6343. _ZIP=$1
  6344.  
  6345. if   [ $# = 1 ];then
  6346.      printf "$_ZIP\n" | egrep '^[0-9][0-9][0-9][0-9][0-9]$' >>/dev/null
  6347.      if   [ $? = 0 ];then
  6348.           printf "Your 10 Day Weather Forecast as follows:\n";
  6349.           lynx -dump "http://www.weather.com/weather/print/$_ZIP" | sed -n '/%$/s/\[.*\]//p';
  6350.           printf "\n"
  6351.      elif [ $? = 1 ];then
  6352.           printf "Bad ZIP code!\n"
  6353.      fi
  6354. elif [ $# != 1 ];then
  6355.      printf "You need to supply a ZIP code!\n"
  6356. fi
  6357. }
  6358.  
  6359.  
  6360.  
  6361. ###### get sunrise and sunset times
  6362. function suntimes()
  6363. {
  6364. l=12765843;curl -s http://weather.yahooapis.com/forecastrss?w=$l|grep astronomy| awk -F\" '{print $2 "\n" $4;}'
  6365. }
  6366.  
  6367.  
  6368.  
  6369. ###### weather by US zip code - Can be called two
  6370. # ways  # weather 50315 # weather "Des
  6371. # Moines"
  6372. function weather()
  6373. {
  6374. declare -a WEATHERARRAY
  6375. WEATHERARRAY=( `lynx -dump http://google.com/search?q=weather+$1 | grep -A 5 '^ *Weather for' | grep -v 'Add to'`)
  6376. echo ${WEATHERARRAY[@]}
  6377. }
  6378.  
  6379.  
  6380.  
  6381. ##################################################
  6382. # Easily run a program in the background without #
  6383. # losing output                  #
  6384. ##################################################
  6385.  
  6386. function fork() { tf=$(tempfile -d /tmp -p $1.);echo -n "$tf "; $@ &>$tf& }
  6387.  
  6388.  
  6389.  
  6390. ##################################################
  6391. # Get FreeMusicCharts of the current month   #
  6392. ##################################################
  6393.  
  6394. function freemusiccharts()
  6395. {
  6396. wget -O - "http://www.darkerradio.com/news/free-music-charts-$(date "+%B-%Y")/" 2> /dev/null | grep -o "http://[^ \"']*\.mp3" |grep "freemusiccharts.songs" | sort | uniq | xargs -n1 wget -c
  6397. }
  6398.  
  6399.  
  6400.  
  6401. ##################################################
  6402. # Find all bash functions in a file      #
  6403. ##################################################
  6404.  
  6405. ###### finds all functions defined in any shell script secified, including .bashrc
  6406. function functions() { read -p "File name> "; sort -d $REPLY | grep "(){" | sed -e 's/(){//g' | less; }
  6407.  
  6408.  
  6409.  
  6410. ##################################################
  6411. # ISO-maker from disc                #
  6412. ##################################################
  6413.  
  6414. function geniso() {
  6415.     # copyright 2007 - 2010 Christopher Bratusek
  6416.     if [[ $CD_WRITER ]]; then
  6417.         dd $DD_OPTS if=$CD_WRITER of="$1"
  6418.     else    dd $DD_OPTS if=/dev/dvdrw of="$1"
  6419.     fi
  6420. }
  6421.  
  6422.  
  6423.  
  6424. ##################################################
  6425. # Extract a particular column of space-      #
  6426. # separated output               #
  6427. ##################################################
  6428.  
  6429. ###### e.g.: lsof | getcolumn 0 | sort | uniq
  6430. function getcolumn() { perl -ne '@cols = split; print "$cols['$1']\n"' ; }
  6431.  
  6432.  
  6433.  
  6434. ##################################################
  6435. # Download the latest kernel             #
  6436. ##################################################
  6437.  
  6438. function get_kernel() {
  6439.     # copyright 2007 - 2010 Christopher Bratusek
  6440.     if [[ $1 == "-s" ]]; then
  6441.         wget http://www.kernel.org/pub/linux/kernel/v2.6/linux-${2}.tar.bz2
  6442.     elif [[ $1 == "-t" ]]; then
  6443.         wget http://www.kernel.org/pub/linux/kernel/v2.6/testing/linux-${2}.tar.bz2
  6444.     elif [[ $1 == "-sg" ]]; then
  6445.         git clone git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-${2}.y.git
  6446.     elif [[ $1 == "-tg" ]]; then
  6447.         git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git
  6448.     elif [[ $1 == "-z" ]]; then
  6449.         wget http://downloads.zen-kernel.org/${2}/${2}-zen${3}.patch.lzma
  6450.     fi
  6451. }
  6452.  
  6453.  
  6454.  
  6455. ##################################################
  6456. # Git stuff                  #
  6457. ##################################################
  6458.  
  6459. ###### copyright 2007 - 2010 Christopher Bratusek
  6460. function git_action() {
  6461.     if [[ -d .git ]]; then
  6462.         if [[ -f .git/dotest/rebasing ]]; then
  6463.             ACTION="rebase"
  6464.         elif [[ -f .git/dotest/applying ]]; then
  6465.             ACTION="apply"
  6466.         elif [[ -f .git/dotest-merge/interactive ]]; then
  6467.             ACTION="rebase -i"
  6468.         elif [[ -d .git/dotest-merge ]]; then
  6469.             ACTION="rebase -m"
  6470.         elif [[ -f .git/MERGE_HEAD ]]; then
  6471.             ACTION="merge"
  6472.         elif [[ -f .git/index.lock ]]; then
  6473.             ACTION="locked"
  6474.         elif [[ -f .git/BISECT_LOG ]]; then
  6475.             ACTION="bisect"
  6476.         else    ACTION="nothing"
  6477.         fi
  6478.         echo $ACTION
  6479.     else    echo --
  6480.     fi
  6481. }
  6482.  
  6483.  
  6484.  
  6485. function git_branch() {
  6486.     if [[ -d .git ]]; then
  6487.         BRANCH=$(git symbolic-ref HEAD 2>/dev/null)
  6488.         echo ${BRANCH#refs/heads/}
  6489.     else    echo --
  6490.     fi
  6491. }
  6492.  
  6493.  
  6494.  
  6495. function git_bzip() {
  6496.     git archive master | bzip2 -9 >"$PWD".tar.bz2
  6497. }
  6498.  
  6499.  
  6500.  
  6501. function git_e() {
  6502.     if [[ "$SVN_USER_ENLIGTENMENT" && $1 == "-m" ]]; then
  6503.         svn co svn+ssh://"$SVN_USER_ENLIGTENMENT"@svn.enlightenment.org/var/svn/$2
  6504.     else
  6505.         svn co http://svn.enlightenment.org/svn/$2
  6506.     fi
  6507. }
  6508.  
  6509.  
  6510.  
  6511. function git_export() {
  6512.     if [[ "$1" != "" ]]; then
  6513.         git checkout-index --prefix="$1"/ -a
  6514.     fi
  6515. }
  6516.  
  6517.  
  6518.  
  6519. function git_gnome() {
  6520.     if [[ $GIT_USER_GNOME ]]; then
  6521.         if [[ $1 == "-m" ]]; then
  6522.             git clone git+ssh://$GIT_USER_GNOME@git.gnome.org/git/$2
  6523.         elif [[ $1 == "-mb" ]]; then
  6524.             git clone -b $3 git+ssh://$GIT_USER_GNOME@git.gnome.org/git/$2
  6525.         fi
  6526.     fi
  6527.     if [[ $1 == "-b" ]]; then
  6528.         git clone -b $3 git://git.gnome.org/$2
  6529.     else    git clone git://git.gnome.org/$1
  6530.     fi
  6531. }
  6532.  
  6533.  
  6534.  
  6535. function git_kde() {
  6536.     if [[ "$SVN_USER_KDE" ]]; then
  6537.         if [[ $1 == "-m" ]]; then
  6538.             svn co --user-name="$SVN_USER_KDE" svn+ssh://svn.kde.org/home/kde/trunk/KDE/$2
  6539.         elif [[ $1 == "-mb" ]]; then
  6540.             svn co --user-name="$SVN_USER_KDE" svn+ssh://svn.kde.org/home/kde/branches/KDE/$2
  6541.         fi
  6542.     fi
  6543.     if [[ $1 == "-b" ]]; then
  6544.         svn co svn://svn.kde.org/home/kde/branches/KDE/$2
  6545.     else    svn co svn://svn.kde.org/home/kde/trunk/KDE/$2
  6546.     fi
  6547. }
  6548.  
  6549.  
  6550.  
  6551. function git_revision() {
  6552.     if [[ -d .git ]]; then
  6553.         REVISION=$(git rev-parse HEAD 2>/dev/null)
  6554.         REVISION=${REVISION/HEAD/}
  6555.         echo ${REVISION:0:6}
  6556.     else    echo --
  6557.     fi
  6558. }
  6559.  
  6560.  
  6561.  
  6562. function git_xfce() {
  6563.     if [[ $GIT_USER_XFCE ]]; then
  6564.         if [[ $1 == "-m" ]]; then
  6565.             git clone ssh://$GIT_USER_XFCE@git.xfce.org/git/$2
  6566.         elif [[ $1 == "-mb" ]]; then
  6567.             git clone -b $3 ssh://$GIT_USER_XFCE@git.xfce.org/git/$2
  6568.         fi
  6569.     fi
  6570.     if [[ $1 == "-b" ]]; then
  6571.         git clone -b $3 git://git.xfce.org/$2
  6572.     else    git clone git://git.xfce.org/$1
  6573.     fi
  6574. }
  6575.  
  6576.  
  6577.  
  6578. function git_xz() {
  6579.     git archive master | xz -9 > "$PWD".tar.xz
  6580. }
  6581.  
  6582.  
  6583.  
  6584. function gup() {
  6585.   git fetch && git rebase origin/$(git branch | grep '^\*' | cut -d\  -f2)
  6586. }
  6587.  
  6588.  
  6589.  
  6590. ###### display the revision number of the current repository                     #
  6591. function svn_rev() {
  6592.     svn info $@ | awk '/^Revision:/ {print $2}'
  6593. }
  6594.  
  6595.  
  6596.  
  6597. ###### do a svn update and show the log messages since the last update
  6598. function svn_uplog() {
  6599.     local old_revision=`svn_rev $@`
  6600.     local first_update=$((${old_revision} + 1))
  6601.  
  6602.     svn up -q $@
  6603.     if [ $(svn_rev $@) -gt ${old_revision} ]
  6604.     then
  6605.         svn log -v -rHEAD:${first_update} $@
  6606.     else
  6607.         echo "No Changes."
  6608.     fi
  6609. }
  6610.  
  6611.  
  6612.  
  6613. ##################################################
  6614. # Grep, grep, grep               #
  6615. ##################################################
  6616.  
  6617. ###### to grep through files found by find, e.g. grepf pattern '*.c'
  6618. # note that 'grep -r pattern dir_name' is an alternative if want all files
  6619. function grepfind() { find . -type f -name "$2" -print0 | xargs -0 grep "$1" ; }
  6620.  
  6621.  
  6622.  
  6623. ###### to grep through the /usr/include directory
  6624. function grepincl() { (cd /usr/include; find . -type f -name '*.h' -print0 | xargs -0 grep "$1" ) ; }
  6625.  
  6626.  
  6627.  
  6628. ###### hgrep, hgrepl (I use these so much I miss them not being on my other machines and should copy them over)
  6629. function hgrepl() {
  6630. history | sed s/.*\ \ // | grep $@
  6631. }
  6632.  
  6633.  
  6634.  
  6635. function hgrep() {
  6636. history | sed s/.*\ \ // | grep $@ | tail -n 30
  6637. }
  6638.  
  6639.  
  6640.  
  6641. function hhgrep() {
  6642. history | egrep "$@" | egrep -v "hgrep $@"
  6643. }
  6644.  
  6645.  
  6646.  
  6647. ##################################################
  6648. # Cool History Summerizer            #
  6649. ##################################################
  6650.  
  6651. function historyawk() { history|awk '{a[$2]++}END{for(i in a){printf"%5d\t%s\n",a[i],i}}'|sort -nr|head; }
  6652.  
  6653.  
  6654.  
  6655. ##################################################
  6656. # Get just the HTTP headers from a web page  #
  6657. # (and its redirects)                #
  6658. ##################################################
  6659.  
  6660. function http_headers() { /usr/bin/curl -I -L $@ ; }
  6661.  
  6662.  
  6663.  
  6664. ##################################################
  6665. # :h gets you to the vim help menu or directly   #
  6666. # to :help wordname              #
  6667. ##################################################
  6668.  
  6669. function :h() {  vim --cmd ":silent help $@" --cmd "only"; }
  6670.  
  6671.  
  6672.  
  6673. ##################################################
  6674. # Show computer information of all sorts     #
  6675. # (requires 'gawk': sudo apt-get install gawk)   #
  6676. ##################################################
  6677.  
  6678. ###### machine details
  6679. function ii()
  6680. {
  6681.     echo -e "\n${RED}You are logged onto:$NC " ; hostname
  6682.     echo -e "\n${RED}Additionnal information:$NC " ; uname -a
  6683.     echo -e "\n${RED}Users logged on:$NC " ; w -h
  6684.     echo -e "\n${RED}Current date:$NC " ; date
  6685.     echo -e "\n${RED}Machine stat:$NC " ; uptime
  6686.     echo -e "\n${RED}Disk space:$NC " ; df -h
  6687.     echo -e "\n${RED}Memory stats (in MB):$NC " ;
  6688.     if [ "$OS" = "Linux" ]; then
  6689.         free -m
  6690.     elif [ "$OS" = "Darwin" ]; then
  6691.         vm_stat
  6692.     fi
  6693.     echo -e "\n${RED}IPs:$NC " ; ips
  6694. }
  6695.  
  6696.  
  6697.  
  6698. function show_battery_load()
  6699. # copyright 2007 - 2010 Christopher Bratusek
  6700. {
  6701.     case $1 in
  6702.         *acpi )
  6703.             check_opt acpi show_battery_load::acpi
  6704.             if [[ $? != "1" ]]; then
  6705.                 load=$(acpi -b | sed -e "s/.* \([1-9][0-9]*\)%.*/\1/")
  6706.                 out="$(acpi -b)"
  6707.                 state="$(echo "${out}" | awk '{print $3}')"
  6708.                 case ${state} in
  6709.                     charging,)
  6710.                         statesign="^"
  6711.                     ;;
  6712.                     discharging,)
  6713.                         statesign="v"
  6714.                     ;;
  6715.                     charged,)
  6716.                         statesign="°"
  6717.                     ;;
  6718.                 esac
  6719.                 battery="${statesign}${load}"
  6720.                 echo $battery
  6721.             fi
  6722.         ;;
  6723.         *apm )
  6724.             check_opt apm show_battery_load::apm
  6725.             if [[ $? != "1" ]]; then
  6726.                 result="$(apm)"
  6727.                 case ${result} in
  6728.                     *'AC on'*)
  6729.                         state="^"
  6730.                     ;;
  6731.                     *'AC off'*)
  6732.                         state="v"
  6733.                     ;;
  6734.                 esac
  6735.                 load="${temp##* }"
  6736.                 battery="${state}${load}"
  6737.                 echo $battery
  6738.             fi
  6739.         ;;
  6740.         * )
  6741.             echo -e "\n${ewhite}Usage:\n"
  6742.             echo -e "${eorange}show_battery_load${ewhite} |${egreen} --acpi${eiceblue} [show batteryload using acpi]\
  6743.             \n${eorange}show_battery_load${ewhite} |${egreen} --apm${eiceblue} [show batteryload using apm]" | column -t
  6744.             echo ""
  6745.             tput sgr0
  6746.         ;;
  6747.     esac
  6748. }
  6749.  
  6750.  
  6751.  
  6752. function show_cpu_load()
  6753. # copyright 2007 - 2010 Christopher Bratusek
  6754. {
  6755.     case $1 in
  6756.         *help )
  6757.             echo -e "\n${ewhite}Usage:\n"
  6758.             echo -e "${eorange}show_cpu_load${ewhite} |${egreen} ! no options !\n"
  6759.             tput sgr0
  6760.         ;;
  6761.         * )
  6762.             NICE_IGNORE=20
  6763.             t="0"
  6764.             while read cpu ni; do
  6765.                 if [[ $ni == *-* || $ni -le $NICE_IGNORE ]]; then
  6766.                     t="$t + $cpu"
  6767.                 fi
  6768.                 if [[ ${cpu%%.*} -eq 0 ]]; then
  6769.                     break
  6770.                 fi
  6771.             done < <(ps -Ao "%cpu= ni="| sort -r)
  6772.             cpu=$(echo "$t" | bc)
  6773.             if [[ ! "${cpu#.}x" = "${cpu}x" ]]; then
  6774.                 cpu="0${cpu}"
  6775.             fi
  6776.             cpu=${cpu%%.*}
  6777.             if [[ $cpu -gt 100 ]]; then
  6778.                 cpu=100
  6779.             fi
  6780.             if [[ $cpu -lt 16 ]]; then
  6781.                 color=${eiceblue}
  6782.             elif [[ $cpu -lt 26 ]]; then
  6783.                 color=${eturqoise}
  6784.             elif [[ $cpu -lt 41 ]]; then
  6785.                 color=${esmoothgreen}
  6786.             elif [[ $cpu -lt 61 ]]; then
  6787.                 color=${egreen}
  6788.             elif [[ $cpu -lt 81 ]]; then
  6789.                 color=${eyellow}
  6790.             else    color=${ered}
  6791.             fi
  6792.             if [[ $cpu -lt 10 ]]; then
  6793.                 prepend=00
  6794.             elif [[ $cpu -lt 100 ]]; then
  6795.                 prepend=0
  6796.             fi
  6797.             if [[ $enabcol == true ]]; then
  6798.                 echo -e "$color$prepend$cpu"
  6799.             else    echo $prepend$cpu
  6800.             fi
  6801.         ;;
  6802.     esac
  6803. }
  6804.  
  6805.  
  6806.  
  6807. function show_mem() {
  6808.     # copyright 2007 - 2010 Christopher Bratusek
  6809.     case $1 in
  6810.         *used )
  6811.             used=$(free -m | grep 'buffers/cache' | awk '{print $3}')
  6812.             if [[ $used -lt 1000 ]]; then
  6813.                 echo 0$used
  6814.             elif [[ $used -lt 100 ]]; then
  6815.                 echo 00$used
  6816.             else    echo $used
  6817.             fi
  6818.         ;;
  6819.         *free )
  6820.             free=$(free -m | grep 'buffers/cache' | awk '{print $4}')
  6821.             if [[ $free -lt 1000 ]]; then
  6822.                 echo 0$free
  6823.             elif [[ $free -lt 100 ]]; then
  6824.                 echo 00$ree
  6825.             else    echo $free
  6826.             fi
  6827.         ;;
  6828.         *used-percent )
  6829.             free | {
  6830.                 read
  6831.                 read m t u f s b c;
  6832.                 f=$[$f + $b + $c]
  6833.                 f=$[100-100*$f/$t]
  6834.                 if [ $f -gt 100 ]; then
  6835.                     f=100
  6836.                 fi
  6837.                 echo ${f}%
  6838.         }
  6839.         ;;
  6840.         *free-percent )
  6841.             free | {
  6842.                 read
  6843.                 read m t u f s b c;
  6844.                 f=$[$f + $b + $c]
  6845.                 f=$[100-100*$f/$t]
  6846.                 if [ $f -gt 100 ]; then
  6847.                     f=100
  6848.                 fi
  6849.                 echo $((100-${f}))%
  6850.                 }
  6851.         ;;
  6852.         * )
  6853.             echo -e "\n${ewhite}Usage:\n"
  6854.             echo -e "\n${eorange}show_mem ${ewhite}|${egreen} --used ${eiceblue}[display used memory in mb]\
  6855.             \n${eorange}show_mem ${ewhite}|${egreen} --free ${eiceblue}[display free memory in mb]\
  6856.             \n${eorange}show_mem ${ewhite}|${egreen} --percent-used ${eiceblue}[display used memory in %]\
  6857.             \n${eorange}show_mem ${ewhite}|${egreen} --percent-free ${eiceblue}[display free memory in %]" | column -t
  6858.             echo ""
  6859.             tput sgr0
  6860.         ;;
  6861.     esac
  6862. }
  6863.  
  6864.  
  6865.  
  6866. function show_size()
  6867. # copyright 2007 - 2010 Christopher Bratusek
  6868. {
  6869.     case $1 in
  6870.         *help )
  6871.             echo -e "\n${ewhite}Usage:\n"
  6872.             echo -e "${eorange}show_size ${ewhite}|${egreen} ! no options !\n"
  6873.             tput sgr0
  6874.         ;;
  6875.         * )
  6876.             let TotalBytes=0
  6877.             for Bytes in $(ls -lA -1 | grep "^-" | awk '{ print $5 }'); do
  6878.                 let TotalBytes=$TotalBytes+$Bytes
  6879.             done
  6880.             if [ $TotalBytes -lt 1024 ]; then
  6881.                 TotalSize=$(echo -e "scale=1 \n$TotalBytes \nquit" | bc)
  6882.                 suffix="B"
  6883.             elif [ $TotalBytes -lt 1048576 ]; then
  6884.                 TotalSize=$(echo -e "scale=1 \n$TotalBytes/1024 \nquit" | bc)
  6885.                 suffix="KB"
  6886.             elif [ $TotalBytes -lt 1073741824 ]; then
  6887.                 TotalSize=$(echo -e "scale=1 \n$TotalBytes/1048576 \nquit" | bc)
  6888.                 suffix="MB"
  6889.             else
  6890.                 TotalSize=$(echo -e "scale=1 \n$TotalBytes/1073741824 \nquit" | bc)
  6891.                 suffix="GB"
  6892.             fi
  6893.             echo "${TotalSize} ${suffix}"
  6894.         ;;
  6895.     esac
  6896. }
  6897.  
  6898.  
  6899.  
  6900. function show_space()
  6901. # copyright 2007 - 2010 Christopher Bratusek
  6902. {
  6903.     case $1 in
  6904.         *used-percent )
  6905.             echo $(df | grep -w $2 | gawk '{print $5}')
  6906.         ;;
  6907.         *free-percent )
  6908.             echo $((100-$(df | grep -w $2 | gawk '{print $5}' | sed -e 's/\%//g')))%
  6909.         ;;
  6910.         *used )
  6911.             echo $(df -h | grep -w $2 | gawk '{print $3}')B
  6912.         ;;
  6913.         *free )
  6914.             echo $(df -h | grep -w $2 | gawk '{print $4}')B
  6915.         ;;
  6916.         *total )
  6917.             echo $(df -h | grep -w $2 | gawk '{print $2}')B
  6918.         ;;
  6919.         * )
  6920.             echo -e "\n${ewhite}Usage:\n"
  6921.             echo -e "${eorange}show_space ${ewhite}|${egreen} --used ${eiceblue}[display used space in mb/gb]\
  6922.             \n${eorange}show_space ${ewhite}|${egreen} --free ${eiceblue}[display free space in mb/gb]\
  6923.             \n${eorange}show_space ${ewhite}|${egreen} --percent-used ${eiceblue}[display used space in %]\
  6924.             \n${eorange}show_space ${ewhite}|${egreen} --percent-free ${eiceblue}[display free space in %]" | column -t
  6925.             echo ""
  6926.             tput sgr0
  6927.         ;;
  6928.     esac
  6929. }
  6930.  
  6931.  
  6932.  
  6933. function show_system_load() {
  6934.     # copyright 2007 - 2010 Christopher Bratusek
  6935.     case $1 in
  6936.         1 )
  6937.             load=$(uptime | sed -e "s/.*load average: \(.*\...\), \(.*\...\), \(.*\...\)/\1/" -e "s/ //g")
  6938.         ;;
  6939.         10 )
  6940.             load=$(uptime | sed -e "s/.*load average: \(.*\...\), \(.*\...\), \(.*\...\)/\2/" -e "s/ //g")
  6941.         ;;
  6942.         15 )
  6943.             load=$(uptime | sed -e "s/.*load average: \(.*\...\), \(.*\...\), \(.*\...\)/\3/" -e "s/ //g")
  6944.         ;;
  6945.         *help | "")
  6946.             echo -e "\n${ewhite}Usage:\n"
  6947.             echo -e "${eorange}show_system_load${ewhite} | ${egreen}1 ${eiceblue}[load average for 1 minute]\
  6948.             \n${eorange}show_system_load${ewhite} | ${egreen}10 ${eiceblue}[load average for 10 minutes]\
  6949.             \n${eorange}show_system_load${ewhite} | ${egreen}15 ${eiceblue}[load average for 15 minutes]\n" | column -t
  6950.             tput sgr0
  6951.         ;;
  6952.     esac
  6953.     if [[ $load != "" ]]; then
  6954.     tmp=$(echo $load*100 | bc)
  6955.     load100=${tmp%.*}
  6956.     if [[ $enabcol == true ]]; then
  6957.         if [[ ${load100} -lt 35 ]]; then
  6958.             loadcolor=${eblue}
  6959.         elif [[ ${load100} -ge 35 ]] && [[ ${load100} -lt 120 ]]; then
  6960.             loadcolor=${eiceblue}
  6961.         elif [[ ${load100} -ge 120 ]] && [[ ${load100} -lt 200 ]]; then
  6962.             loadcolor=${egreen}
  6963.         elif [[ ${load100} -ge 200 ]] && [[ ${load100} -lt 300 ]]; then
  6964.             loadcolor=${eyellow}
  6965.         else    loadcolor=${ered}
  6966.         fi
  6967.     fi
  6968.     echo -e $loadcolor$load
  6969.     fi
  6970. }
  6971.  
  6972.  
  6973.  
  6974. function show_tty()
  6975. # copyright 2007 - 2010 Christopher Bratusek
  6976. {
  6977.     case $1 in
  6978.         *help )
  6979.             echo -e "\n${ewhite}Usage:\n"
  6980.             echo -e "${eorange}show_tty${ewhite}|${egreen} ! no options !\n"
  6981.             tput sgr0
  6982.         ;;
  6983.         * )
  6984.             TTY=$(tty)
  6985.             echo ${TTY:5} | sed -e 's/\//\:/g'
  6986.         ;;
  6987.     esac
  6988. }
  6989.  
  6990.  
  6991.  
  6992. function show_uptime() {
  6993.     # copyright 2007 - 2010 Christopher Bratusek
  6994.     case $1 in
  6995.         *help )
  6996.             echo -e "\n${ewhite}Usage:\n"
  6997.             echo -e "${eorange}show_uptime${ewhite} |${egreen} ! no options !\n"
  6998.             tput sgr0
  6999.         ;;
  7000.         * )
  7001.             uptime=$(</proc/uptime)
  7002.             timeused=${uptime%%.*}
  7003.             if (( timeused > 86400 )); then
  7004.             ((
  7005.                 daysused=timeused/86400,
  7006.                 hoursused=timeused/3600-daysused*24,
  7007.                 minutesused=timeused/60-hoursused*60-daysused*60*24,
  7008.                 secondsused=timeused-minutesused*60-hoursused*3600-daysused*3600*24
  7009.             ))
  7010.                 if (( hoursused < 10 )); then
  7011.                     hoursused=0${hoursused}
  7012.                 fi
  7013.                 if (( minutesused < 10 )); then
  7014.                     minutesused=0${minutesused}
  7015.                 fi
  7016.                 if (( secondsused < 10 )); then
  7017.                     secondsused=0${secondsused}
  7018.                 fi
  7019.                 output="${daysused}d ${hoursused}h:${minutesused}m:${secondsused}s"
  7020.             elif (( timeused < 10 )); then
  7021.                 output="0d 00h:00m:0$(timeused)s"
  7022.             elif (( timeused < 60 )); then
  7023.                 output="0d 00h:00m:${timeused}s"
  7024.             elif (( timeused < 3600 )); then
  7025.             ((
  7026.                 minutesused=timeused/60,
  7027.                 secondsused=timeused-minutesused*60
  7028.             ))
  7029.                 if (( minutesused < 10 )); then
  7030.                     minutesused=0${minutesused}
  7031.                 fi
  7032.                 if (( secondsused < 10 )); then
  7033.                     secondsused=0${secondsused}
  7034.                 fi
  7035.                 output="0d 00h:${minutesused}m:${secondsused}s"
  7036.             elif (( timeused < 86400 )); then
  7037.             ((
  7038.                 hoursused=timeused/3600,
  7039.                 minutesused=timeused/60-hoursused*60,
  7040.                 secondsused=timeused-minutesused*60-hoursused*3600
  7041.             ))
  7042.                 if (( hoursused < 10 )); then
  7043.                     hoursused=0${hoursused}
  7044.                 fi
  7045.                 if (( minutesused < 10 )); then
  7046.                     minutesused=0${minutesused}
  7047.                 fi
  7048.                 if (( secondsused < 10 )); then
  7049.                     secondsused=0${secondsused}
  7050.                 fi
  7051.                 output="0d ${hoursused}h:${minutesused}m:${secondsused}s"
  7052.             fi
  7053.             echo "$output"
  7054.         ;;
  7055.     esac
  7056. }
  7057.  
  7058.  
  7059.  
  7060. ###### STAT Function showing ALL info, stat options, and descriptions
  7061. function statt() { C=c;stat --h|sed '/Th/,/NO/!d;/%/!d'|while read l;do p=${l/% */};[ $p == %Z ]&&C=fc&&echo ^FS:^;echo "`stat -$C $p \"$1\"` ^$p^${l#%* }";done|column -ts^; }
  7062.  
  7063.  
  7064.  
  7065. function system_infos()
  7066. # copyright 2007 - 2010 Christopher Bratusek
  7067. {
  7068.     case $1 in
  7069.         *cpu)
  7070.             echo -e "${ewhite}CPU:\n"
  7071.             echo -e "${eorange}Model:${eiceblue} $(grep "model name" /proc/cpuinfo | sed -e 's/.*: //g')"
  7072.             echo -e "${eorange}MHz  :${eiceblue} $(grep "cpu MHz" /proc/cpuinfo | sed -e 's/.*: //g')\n"
  7073.         ;;
  7074.         *kernel)
  7075.             echo -e "${ewhite}Kernel:\n"
  7076.             echo -e "${eorange}Release:${eiceblue} $(uname -r)"
  7077.             echo -e "${eorange}Version:${eiceblue} $(uname -v)"
  7078.             echo -e "${eorange}Machine:${eiceblue} $(uname -m)\n"
  7079.         ;;
  7080.         *mem | *ram)
  7081.             echo -e "${ewhite}RAM:\n"
  7082.             echo -e "${eorange}Total:${eiceblue} $(((`showmem --free`) + (`showmem --used`))) MB"
  7083.             echo -e "${eorange}Free :${eiceblue} $(showmem --free) MB"
  7084.             echo -e "${eorange}Used :${eiceblue} $(showmem --used) MB\n"
  7085.         ;;
  7086.         *partitions)
  7087.             echo -e "${ewhite}Partitions:${eorange}\n"
  7088.             echo -e "major minor blocks device-node ${eiceblue}\
  7089.             \n$(cat /proc/partitions | sed -e '1,2d')" | column -t
  7090.             echo ""
  7091.         ;;
  7092.         *pci)
  7093.             check_opt lspci systeminfos::pci
  7094.             if [[ $? != "1" ]]; then
  7095.                 echo -e "${ewhite}PCI Devices:\n${eiceblue}"
  7096.                 lspci -vkmm
  7097.                 echo ""
  7098.             fi
  7099.         ;;
  7100.         *usb)
  7101.             check_opt lsusb systeminfos::usb
  7102.             if [[ $? != "1" ]]; then
  7103.                 echo -e "${ewhite}USB Devices:\n${eiceblue}"
  7104.                 lsusb -v
  7105.                 echo ""
  7106.             fi
  7107.         ;;
  7108.         *mounts)
  7109.             echo -e "${ewhite}Mounts:\n${eorange}\
  7110.             \ndevice-node on mount-point type filesystem options\n" ${eiceblue} "\n\n$(mount)" | column -t
  7111.             echo ""
  7112.         ;;
  7113.         *bios)
  7114.             check_opt dmidecode systeminfos::bios
  7115.             if [[ $? != "1" && $EUID == 0 ]]; then
  7116.                 echo -e "${ewhite}SMBIOS/DMI Infos:${eiceblue}\n"
  7117.                 dmidecode -q
  7118.             fi
  7119.         ;;
  7120.         *all)
  7121.             system_infos_cpu
  7122.             system_infos_kernel
  7123.             system_infos_memory
  7124.             system_infos_partitions
  7125.             # system_infos_pci
  7126.             # system_infos_usb
  7127.             system_infos_mounts
  7128.             # system_infos_bios
  7129.         ;;
  7130.         *)
  7131.             echo -e "\n${ewhite}Usage:\n"
  7132.             echo -e "${eorange}system_infos ${ewhite}|${egreen} --cpu\t\t${eiceblue}[Display CPU Model and Freq]\
  7133.             \n${eorange}system_infos ${ewhite}|${egreen} --kernel\t${eiceblue}  [Display Kernel Version, Release and Machine]\
  7134.             \n${eorange}system_infos ${ewhite}|${egreen} --memory\t${eiceblue}  [Display Total, Free and Used RAM]\
  7135.             \n${eorange}system_infos ${ewhite}|${egreen} --partitions\t${eiceblue}[Display Major, Minor, Blocks and Node for all Paritions]\
  7136.             \n${eorange}system_infos ${ewhite}|${egreen} --pci\t\t${eiceblue}[Display Infos about all PCI Devices (and their kernel-module)]\
  7137.             \n${eorange}system_infos ${ewhite}|${egreen} --usb\t\t${eiceblue}[Display Infos about all USB Devices (and their kernel-module)]\
  7138.             \n${eorange}system_infos ${ewhite}|${egreen} --bios\t${eiceblue}    [Display SMBIOS DMI Infos]\
  7139.             \n${eorange}system_infos ${ewhite}|${egreen} --mounts\t${eiceblue}  [Display all mounted devices]\n"
  7140.             tput sgr0
  7141.         ;;
  7142.     esac
  7143. }
  7144.  
  7145.  
  7146.  
  7147. ###### shows various info on running activities
  7148. # copyright 2007 - 2010 Christopher Bratusek
  7149. function treeps() {
  7150.     ps f -u $USER -o command,pid,%cpu,%mem,time,etime,tty | \
  7151.         awk 'NR <= 1 {print;next} !/awk/ && $0~var' var=${1:-".*"}
  7152. }
  7153.  
  7154.  
  7155.  
  7156. ###### info about current open windows
  7157. # copyright 2007 - 2010 Christopher Bratusek
  7158. function wininfo() {
  7159.     xprop | grep -w "WM_NAME\|WM_CLASS\|WM_WINDOW_ROLE\|_NET_WM_STATE"
  7160. }
  7161.  
  7162.  
  7163.  
  7164. ##################################################
  7165. # Resizing an image              #
  7166. ##################################################
  7167.  
  7168. # USAGE: image_resize "percentage of image resize" "input image" "output image"
  7169. function image_resize()
  7170. {
  7171. convert -sample "$1"%x"$1"% "$2" "$3"
  7172. }
  7173.  
  7174.  
  7175.  
  7176. ##################################################
  7177. # Search IMDB.COM                #
  7178. ##################################################
  7179.  
  7180. function imdb()
  7181. {
  7182. firefox "http://www.imdb.com/find?s=all&q="${@}"&x=0&y=0" &
  7183. }
  7184.  
  7185.  
  7186.  
  7187. ##################################################
  7188. # INC                        #
  7189. ##################################################
  7190.  
  7191. function inc() {
  7192.     let OPS=$OPS+1
  7193.     echo "* pcur $OPS"
  7194. }
  7195.  
  7196.  
  7197.  
  7198. ##################################################
  7199. # Displays metadata for specified media file     #
  7200. ##################################################
  7201.  
  7202. ######   $1 = media file name
  7203. function info() {
  7204.     EXT=`echo "${1##*.}" | sed 's/\(.*\)/\L\1/'`
  7205.     if [ "$EXT" == "mp3" ]; then
  7206.         id3v2 -l "$1"
  7207.         echo
  7208.         mp3gain -s c "$1"
  7209.     elif [ "$EXT" == "flac" ]; then
  7210.         metaflac --list --block-type=STREAMINFO,VORBIS_COMMENT "$1"
  7211.     else
  7212.         echo "ERROR: Not a supported file type."
  7213.     fi
  7214. }
  7215.  
  7216.  
  7217.  
  7218. ##################################################
  7219. # Sample introduction                #
  7220. ##################################################
  7221.  
  7222. function intro() {
  7223. less <<INTRO
  7224. Hi, welcome to your bytesized shell :)
  7225. We've added a few shell aliases (commands) for common
  7226. things, to make your life easier, here's a quick list of
  7227. things you might want to do:
  7228. command - what it does
  7229. For more advances users:
  7230. press "q" to exit this screen
  7231. This screen will not be displayed to you in the future, if you want to see it again, type "intro"
  7232. INTRO
  7233. }
  7234.  
  7235.  
  7236.  
  7237. ##################################################
  7238. # Kill a process by name             #
  7239. ##################################################
  7240.  
  7241. ###### example: killps firefox-bin
  7242. function killps()
  7243. {
  7244.     local pid pname sig="-TERM" # default signal
  7245.     if [ "$#" -lt 1 ] || [ "$#" -gt 2 ]; then
  7246.         echo "Usage: killps [-SIGNAL] pattern"
  7247.         return;
  7248.     fi
  7249.     if [ $# = 2 ]; then sig=$1 ; fi
  7250.     for pid in $(myps | nawk '!/nawk/ && $0~pat { print $2 }' pat=${!#}) ; do
  7251.         pname=$(myps | nawk '$2~var { print $6 }' var=$pid )
  7252.         if ask "Kill process $pid <$pname> with signal $sig ? "
  7253.             then kill $sig $pid
  7254.         fi
  7255.     done
  7256. }
  7257.  
  7258.  
  7259.  
  7260. ###### example: pskill firefox-bin
  7261. # copyright 2007 - 2010 Christopher Bratusek
  7262. function psgrep() {
  7263.     if [[ $1 == "-u" ]]; then
  7264.         ps aux | grep -v grep | grep $2 | awk '{ print $2 " : " $11}' | tee .temp
  7265.         CMDS=$(cat .temp)
  7266.     elif [[ $1 != "" ]]; then
  7267.         ps aux | grep -v grep | grep "$1" | awk '{ print $11 " : " $2 " : " $1 }' | tee .temp
  7268.         CMDS=$(cat .temp)
  7269.     fi
  7270.     if [[ $CMDS == "" ]]; then
  7271.         echo "no matching process"
  7272.     fi
  7273.     rm -f .temp
  7274. }
  7275.  
  7276.  
  7277.  
  7278. function pskill() {
  7279.     if [[ $1 ]]; then
  7280.         psgrep $1
  7281.         shift
  7282.         if [[ $CMDS != "" ]]; then
  7283.             echo -e "\nenter process number to kill:\n"
  7284.             read ID
  7285.             if [[ ! $ID == 0 || ! $ID == "" ]]; then
  7286.                 kill $@ $ID
  7287.             fi
  7288.         fi
  7289.     fi
  7290. }
  7291.  
  7292.  
  7293.  
  7294. ##################################################
  7295. # Led set and reset              #
  7296. ##################################################
  7297.  
  7298. function kitt() {
  7299.     # copyright 2007 - 2010 Christopher Bratusek
  7300.     setleds -L -num;
  7301.     setleds -L -caps;
  7302.     setleds -L -scroll;
  7303.     while :; do
  7304.         setleds -L +num;
  7305.         sleep 0.2;
  7306.         setleds -L -num;
  7307.         setleds -L +caps;
  7308.         sleep 0.2;
  7309.         setleds -L -caps;
  7310.         setleds -L +scroll;
  7311.         sleep 0.2;
  7312.         setleds -L -scroll;
  7313.         setleds -L +caps;
  7314.         sleep 0.2;
  7315.         setleds -L -caps;
  7316.     done
  7317.     resetleds
  7318. }
  7319.  
  7320.  
  7321.  
  7322. function resetleds()
  7323. # copyright 2007 - 2010 Christopher Bratusek
  7324. {
  7325.     setleds -L < /dev/tty1
  7326. }
  7327.  
  7328.  
  7329.  
  7330. ##################################################
  7331. # Concatenate stuff              #
  7332. ##################################################
  7333.  
  7334. function kitty() {
  7335.     # copyright 2007 - 2010 Christopher Bratusek
  7336.     cat -n "$@"
  7337. }
  7338.  
  7339.  
  7340.  
  7341. ##################################################
  7342. # Advanced ls functions              #
  7343. ##################################################
  7344.  
  7345. function la() {
  7346.     # copyright 2007 - 2010 Christopher Bratusek
  7347.     ls -A --group-directories-first "$@"
  7348. }
  7349.  
  7350.  
  7351.  
  7352. function lg() {
  7353.     # copyright 2007 - 2010 Christopher Bratusek
  7354.     if [[ "$@" == "" ]]; then
  7355.         $@="*"
  7356.     fi
  7357.     ls -l --group-directories-first "$@" | gawk '{print $9, "belongs to Group ->", $4}' | column -t
  7358. }
  7359.  
  7360.  
  7361.  
  7362. function ll() {
  7363.     # copyright 2007 - 2010 Christopher Bratusek
  7364.     ls -l --group-directories-first "$@"
  7365. }
  7366.  
  7367.  
  7368.  
  7369. ###### Counts files, subdirectories and directory size and displays details
  7370. # about files depending on the available space
  7371. function lls() {
  7372.     # count files
  7373.     echo -n "<`find . -maxdepth 1 -mindepth 1 -type f | wc -l | tr -d '[:space:]'` files>"
  7374.     # count sub-directories
  7375.     echo -n " <`find . -maxdepth 1 -mindepth 1 -type d | wc -l | tr -d '[:space:]'` dirs/>"
  7376.     # count links
  7377.     echo -n " <`find . -maxdepth 1 -mindepth 1 -type l | wc -l | tr -d '[:space:]'` links@>"
  7378.     # total disk space used by this directory and all subdirectories
  7379.     echo " <~`du -sh . 2> /dev/null | cut -f1`>"
  7380.     ROWS=`stty size | cut -d' ' -f1`
  7381.     FILES=`find . -maxdepth 1 -mindepth 1 |
  7382.     wc -l | tr -d '[:space:]'`
  7383.     # if the terminal has enough lines, do a long listing
  7384.     if [ `expr "${ROWS}" - 6` -lt "${FILES}" ]; then
  7385.         ls
  7386.     else
  7387.         ls -hlAF --full-time
  7388.     fi
  7389. }
  7390.  
  7391.  
  7392.  
  7393. function lo() {
  7394.     # copyright 2007 - 2010 Christopher Bratusek
  7395.     if [[ "$@" == "" ]]; then
  7396.         $@="*"
  7397.     fi
  7398.     ls -l --group-directories-first "$@" | gawk '{print $9, "belongs to User ->", $3}' | sed -e '1d' | column -t
  7399. }
  7400.  
  7401.  
  7402.  
  7403. function l1() {
  7404.     # copyright 2007 - 2010 Christopher Bratusek
  7405.     ls -1 --group-directories-first "$@"
  7406. }
  7407.  
  7408.  
  7409.  
  7410.  
  7411. function lm() {
  7412.     # copyright 2007 - 2010 Christopher Bratusek
  7413.     if [[ ! "$@" == "" ]]; then
  7414.         for file in "$@"; do
  7415.             stat -c "%A %a %n" "$file" | gawk '{print "Permissions of:", $3, "->", $1, "("$2")"}'
  7416.         done | column -t
  7417.     fi
  7418. }
  7419.  
  7420.  
  7421.  
  7422. ###### inspired by http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x279.html
  7423. # but I made it a single awk instead of an awk, forloop and a bc
  7424. # asumes we have awk available.  but really, who doesnt have awk?
  7425. # let's get the size of the files in this dir
  7426. function lsbytes() {
  7427.     echo -n $(ls -l | awk '/^-/{total += $5} END{printf "%.2f", total/1048576}')
  7428. }
  7429.  
  7430.  
  7431.  
  7432. function lscd() {
  7433.     # copyright 2007 - 2010 Christopher Bratusek
  7434.     builtin cd "${@}" &>/dev/null
  7435.     . $BSNG_RC_DIR/dirinfo/display
  7436.     dirinfo_display
  7437.     echo -e "${epink}content:"
  7438.     ls $LSCD_OPTS
  7439.     echo "$PWD" > $HOME/.lastpwd
  7440. }
  7441.  
  7442.  
  7443.  
  7444. ###### display long list of files with the given extension
  7445. # example: lsext txt
  7446. function lsext()
  7447. {
  7448. find . -type f -iname '*.'${1}'' -exec ls -l {} \; ;
  7449. }
  7450.  
  7451.  
  7452.  
  7453. ###### another way to call for a list of files/folders
  7454. function lsr() { /bin/ls -l "$@"/..namedfork/rsrc ; }
  7455.  
  7456.  
  7457.  
  7458. ##################################################
  7459. # Uppercase, lowercase, & cleanup strings & names#
  7460. ##################################################
  7461.  
  7462. ###### lowercase all files in the current directory
  7463. function lcfiles() {
  7464.     print -n 'Really lowercase all files? (y/n) '
  7465.     if read -q ; then
  7466.         for i in * ; do
  7467.             mv $i $i:l
  7468.     done
  7469.     fi
  7470. }
  7471.  
  7472.  
  7473.  
  7474. ###### Convert the first letter into lowercase letters
  7475. function lcfirst() {
  7476.       if [ -n "$1" ]; then
  7477.           perl -e 'print lcfirst('$1')'
  7478.       else
  7479.           cat - | perl -ne 'print lcfirst($_)'
  7480.       fi
  7481. }
  7482.  
  7483.  
  7484.  
  7485. ###### move filenames to lowercase
  7486. function lowercase()
  7487. {
  7488.     for file ; do
  7489.         filename=${file##*/}
  7490.         case "$filename" in
  7491.         */*) dirname==${file%/*} ;;
  7492.         *) dirname=.;;
  7493.         esac
  7494.         nf=$(echo $filename | tr A-Z a-z)
  7495.         newname="${dirname}/${nf}"
  7496.         if [ "$nf" != "$filename" ]; then
  7497.             mv "$file" "$newname"
  7498.             echo "lowercase: $file --> $newname"
  7499.         else
  7500.             echo "lowercase: $file not changed."
  7501.         fi
  7502.     done
  7503. }
  7504.  
  7505.  
  7506.  
  7507. ###### Remove whitespace at the beginning of a string
  7508. #  @param string $1 string (optional, can also handle STDIN)
  7509. #  @return string
  7510. #  @example:    echo " That is a sentinece " | trim
  7511. function ltrim() {
  7512.       if [ -n "$1" ]; then
  7513.               echo $1 | sed 's/^[[:space:]]*//g'
  7514.       else
  7515.               cat - | sed 's/^[[:space:]]*//g'
  7516.       fi
  7517. }
  7518.  
  7519.  
  7520.  
  7521. ###### Space removal and lowercases folders in current dir.
  7522. function rmspaces() {
  7523.     ls | while read -r FILE
  7524.         do
  7525.         mv -v "$FILE" `echo $FILE | tr ' ' '_' | tr -d '[{}(),\!]' | tr -d "\'" | tr '[A-Z]' '[a-z]' | sed 's/_-_/_/g'`
  7526.         done
  7527. }
  7528.  
  7529.  
  7530.  
  7531. ###### Remove whitespace at the end of a string
  7532. #  @param string $1 string (optional, can also handle STDIN)
  7533. #  @return string
  7534. #  @example:    echo "That is a sentinece " | rtrim
  7535. function rtrim() {
  7536.       if [ -n "$1" ]; then
  7537.               echo $1 | sed 's/[[:space:]]*$//g'
  7538.       else
  7539.               cat - | sed 's/[[:space:]]*$//g'
  7540.       fi
  7541. }
  7542.  
  7543.  
  7544.  
  7545. ###### Cut a string after X chars and append three points
  7546. # string strim( string string [, int length ] )
  7547. function strim() {
  7548.       local string="$1"
  7549.       local length=${2:-30}
  7550.       [ "${#string}" -gt ${length} ] && string="${string:0:${length}}..."
  7551.       echo $string
  7552. }
  7553.  
  7554.  
  7555.  
  7556. ###### Convert all alphabetic characters to lowercase
  7557. #  @param string $1|STDIN string
  7558. #  @return string
  7559. function strtolower() {
  7560.       if [ -n "$1" ]; then
  7561.         echo $1 | tr '[:upper:]' '[:lower:]'
  7562.       else
  7563.         cat - | tr '[:upper:]' '[:lower:]'
  7564.       fi
  7565. }
  7566.  
  7567.  
  7568.  
  7569. ###### Convert all alphabetic characters converted to uppercase
  7570. #  @param string $1|STDIN string
  7571. #  @return string
  7572. function strtoupper() {
  7573.       if [ -n "$1" ]; then
  7574.         echo $1 | tr '[:lower:]' '[:upper:]'
  7575.       else
  7576.         cat - | tr '[:lower:]' '[:upper:]'
  7577.       fi
  7578. }
  7579.  
  7580.  
  7581.  
  7582. ###### Remove whitespace at the beginning and end of a string
  7583. #  @param string $1 string (optional, can also handle STDIN)
  7584. #  @return string
  7585. #  @example:    echo " That is a sentinece " | trim
  7586. function trim() {
  7587.       if [ -n "$1" ]; then
  7588.               echo $1 | sed 's/^[[:space:]]*//g' | sed 's/[[:space:]]*$//g'
  7589.       else
  7590.               cat - | sed 's/^[[:space:]]*//g' | sed 's/[[:space:]]*$//g'
  7591.       fi
  7592. }
  7593.  
  7594.  
  7595.  
  7596. ###### Convert the first letter into uppercase letters
  7597. function ucfirst() {
  7598.       if [ -n "$1" ]; then
  7599.           perl -e 'print ucfirst('$1')'
  7600.       else
  7601.           cat - | perl -ne 'print ucfirst($_)'
  7602.       fi
  7603. }
  7604.  
  7605.  
  7606.  
  7607.  
  7608. ###### Converts first letter of each word within a string into an uppercase, all other to lowercase
  7609. #     string ucwords( string string )
  7610. function ucwords() {
  7611.       local string="$*"
  7612.       for word in $string; do
  7613.           # Get the first character with cut and convert them into uppercase.
  7614.           local first="$( echo $word | cut -c1 | tr '[:lower:]' '[:upper:]' )"
  7615.           # Convert the rest of the word into lowercase and append them to the first character.
  7616.           word="$first$( echo $word | cut -c2-${#word} | tr '[:upper:]' '[:lower:]' )"
  7617.           # Put together the sentence.
  7618.           local phrase="$phrase $word"
  7619.       done
  7620.       echo "$phrase"
  7621. }
  7622.  
  7623.  
  7624.  
  7625. ##################################################
  7626. # Corporate ldapsearch for users         #
  7627. ##################################################
  7628.  
  7629. function ldapfind() {
  7630.         ldapsearch -x -h ldap.foo.bar.com -b dc=bar,dc=com uid=$1
  7631. }
  7632.  
  7633.  
  7634.  
  7635. ##################################################
  7636. # Organize a text file               #
  7637. ##################################################
  7638.  
  7639. ###### sort lines in a text file
  7640. function linesort()
  7641. {
  7642. sort -u "$1" > "$1".new
  7643. }
  7644.  
  7645.  
  7646.  
  7647. ###### remove duplicate lines in a file (without resorting)
  7648. function removeduplines()
  7649. {
  7650. awk '!x[$0]++' "$1" > "$1".new
  7651. }
  7652.  
  7653.  
  7654.  
  7655. ##################################################
  7656. # Livehttpheaders (firefox addon) replacement    #
  7657. ##################################################
  7658.  
  7659. ###### usage: liveh [-i interface] [output-file] && firefox &
  7660. function liveh() { tcpdump -lnnAs512 ${1-} tcp |sed ' s/.*GET /GET /;s/.*Host: /Host: /;s/.*POST /POST /;/[GPH][EOo][TSs]/!d;w '"${2-liveh.txt}"' ' >/dev/null ; }
  7661.  
  7662.  
  7663.  
  7664. ##################################################
  7665. # Search for music in the specified location     #
  7666. ##################################################
  7667.  
  7668. function locatemusic()
  7669. {
  7670. slocate -i "${1}" | grep "$HOME/Music/";
  7671. }
  7672.  
  7673.  
  7674.  
  7675. ##################################################
  7676. # MPD music stuff                #
  7677. ##################################################
  7678.  
  7679. ###### Add music files in MPD
  7680. function madd()
  7681. {
  7682.     # while [ $# -gt 0 ]; do
  7683.         # case "$1" in
  7684.             # a)
  7685.             # args[i++]=artist;;
  7686.             # b)
  7687.             # args[i++]=album;;
  7688.             # t)
  7689.             # args[i++]=title;;
  7690.             # *)
  7691.             # args[i++]=$1;;
  7692.         # esac; shift;
  7693.     # done
  7694.     # mpc search "${args[@]}" |
  7695.     mpc search "$@" |
  7696.     mpc add
  7697. }
  7698.  
  7699.  
  7700.  
  7701. ###### Clear, add and play: MPD
  7702. function mcap()
  7703. {
  7704.     mpc clear
  7705.     # while [ $# -gt 0 ]; do
  7706.         # case "$1" in
  7707.             # a)
  7708.             # args[i++]=artist;;
  7709.             # b)
  7710.             # args[i++]=album;;
  7711.             # t)
  7712.             # args[i++]=title;;
  7713.             # *)
  7714.             # args[i++]=$1;;
  7715.         # esac; shift; done
  7716.     # mpc search "${args[@]}" |
  7717.     mpc search "$@" |
  7718.     mpc add
  7719.     mpc play
  7720. }
  7721.  
  7722.  
  7723.  
  7724. ##################################################
  7725. # Mailme                     #
  7726. ##################################################
  7727.  
  7728. function mailme()
  7729. {
  7730.     echo "$@" | mail -s "$1" $SERVERMAIL
  7731. }
  7732.  
  7733.  
  7734.  
  7735. ##################################################
  7736. # Manpage to ... document            #
  7737. ##################################################
  7738.  
  7739. ###### example: man2pdf wipe    =   wipe.pdf
  7740. # copyright 2007 - 2010 Christopher Bratusek
  7741. function man2pdf()
  7742. {
  7743.     case $1 in
  7744.         *help | "" )
  7745.             echo -e "\n${ewhite}Usage:"
  7746.             echo -e "\n${eorange}man2pdf${ewhite} |${egreen} <manualpage>${eiceblue} [generate a pdf from <manualpage>]\n"
  7747.             tput sgr0
  7748.         ;;
  7749.         * )
  7750.             check_opt ps2pdf man2pdf
  7751.             if [[ $? != "1"  && $1 ]]; then
  7752.                 man -t $1 | ps2pdf - >$1.pdf
  7753.             else    echo "No manpage given."
  7754.             fi
  7755.         ;;
  7756.     esac
  7757. }
  7758.  
  7759.  
  7760.  
  7761. ###### example: man2text wipe   =   wipe.txt
  7762. function man2text()
  7763. {
  7764. man "$1" | col -b > ~/man_"$1".txt
  7765. }
  7766.  
  7767.  
  7768.  
  7769. ##################################################
  7770. # .. And function                #
  7771. ##################################################
  7772.  
  7773. function man_()
  7774. {
  7775.     for i ; do
  7776.         xtitle The $(basename $1|tr -d .[:digit:]) manual
  7777.         command man -F -a "$i"
  7778.     done
  7779. }
  7780.  
  7781.  
  7782.  
  7783. ##################################################
  7784. # Meta-Backup - backup your software selection   #
  7785. # and repositories in a deb meta package     #
  7786. ##################################################
  7787.  
  7788. function meta-backup()
  7789. {
  7790. ## Written by Arjan van Lent aka socialdefect ## VERSION: 2.1 ## Modified by Inameiname
  7791. DIALOG1="Did you enable extra repositories or PPAs on this system?. If you have no idea what this is just enter no"
  7792. DIALOG2="Your backup has been created succesfully"
  7793. DIALOG3="Something went wrong. Type bash -x meta-backup in a terminal to debug"
  7794. DIALOG4="Would you like to use the backup for a distribution upgrade?"
  7795. DIALOG5="Enter the codename of the distribution you'd like to upgrade to. eg. sid or maverick"
  7796. DIALOG6="Where woud you like to save your backup files? Enter full path. eg /home/username/backups"
  7797. mkdir -p /tmp/meta-backup/my-meta-backup/DEBIAN                     ## creating build directories
  7798.   dialog --title "Meta-backup" --yesno "$DIALOG1" 8 40                  ## repository dialog ## question add repo's
  7799.   dialog --title "Meta-backup" --infobox "..." 8 40
  7800. if [ $? = 0 ] ; then
  7801.   mkdir -p /tmp/meta-backup/my-repo-backup/etc/apt/sources.list.d
  7802.   mkdir /tmp/meta-backup/my-repo-backup/DEBIAN
  7803.   cp -R /etc/apt/sources.list.d/* /tmp/meta-backup/my-repo-backup/etc/apt/sources.list.d/
  7804.   cp -R /etc/apt/sources.list /tmp/meta-backup/my-repo-backup/etc/apt/
  7805. fi
  7806.                                             ## create the control file for the repo-backup
  7807. echo 'Section: misc
  7808. Priority: optional
  7809. Package: my-repo-backup
  7810. Version: 2.1
  7811. Maintainer: meta-backup
  7812. Depends:
  7813. Architecture: all
  7814. Description: Repository/PPA backup created by meta-backup.
  7815. Repository/PPA backup created by meta-backup. This package can be used to install all repositories and PPAs that are installed on the computer where the backup is made.' >> /tmp/meta-backup/my-repo-backup/DEBIAN/control
  7816.                                             ## create the preinst file for the repo-backup
  7817. echo '#!/bin/sh
  7818. set -e
  7819. # Backup repo config
  7820. mv /etc/apt/sources.list /etc/apt/sources.list.old
  7821. mv /etc/apt/sources.list.d /etc/apt/sources.list.d.old' >> /tmp/meta-backup/my-repo-backup/DEBIAN/preinst
  7822. chmod +x /tmp/meta-backup/my-repo-backup/DEBIAN/preinst
  7823.                                             ## create the postinst file for the repo-backup
  7824. echo '#!/bin/sh
  7825. set -e
  7826. # Pubkeys (to generate this large key, which is all of them in one: sudo apt-key exportall > /tmp/repokeys.key)
  7827. if [ -f /tmp/repokeys.key ];then
  7828.     rm /tmp/repokeys.key
  7829. fi
  7830. sudo cat > "/tmp/repokeys.key" <<"End-of-message"' >> /tmp/meta-backup/my-repo-backup/DEBIAN/postinst
  7831.   ## get the repository keys
  7832. apt-key exportall >> /tmp/meta-backup/my-repo-backup/DEBIAN/postinst
  7833. echo 'End-of-message
  7834. if which sudo apt-key >> /dev/null; then
  7835.     if sudo apt-key add "/tmp/repokeys.key"; then
  7836.         echo "OK - repokeys key was installed"
  7837.     else
  7838.         echo "ERROR: there was a problem installing the repokeys-key"
  7839.     fi
  7840. fi
  7841. sudo rm -fv "/tmp/repokeys.key"' >> /tmp/meta-backup/my-repo-backup/DEBIAN/postinst
  7842. chmod +x /tmp/meta-backup/my-repo-backup/DEBIAN/postinst
  7843.                                             ## create the postrm file for the repo-backup
  7844. echo '#!/bin/sh
  7845. set -e
  7846. # Restore repo config
  7847. mv /etc/apt/sources.list.old /etc/apt/sources.list
  7848. mv /etc/apt/sources.list.d.old /etc/apt/sources.list.d' >> /tmp/meta-backup/my-repo-backup/DEBIAN/postrm
  7849. chmod +x /tmp/meta-backup/my-repo-backup/DEBIAN/postrm
  7850. dialog --title "Meta-backup" --yesno "$DIALOG4" 8 40                    ## Distupgrade feature
  7851.   dialog --title "Meta-backup" --infobox "..." 8 40
  7852. if [ $? = 0 ] ; then
  7853.     dialog --title "Meta-backup" --inputbox "$DIALOG5" 8 40 2> /tmp/meta-backup/upgrade
  7854.     UPGRADE=`cat /tmp/meta-backup/upgrade`
  7855.     dialog --title "Meta-backup" --infobox "..." 8 40
  7856. fi
  7857. if [ $UPGRADE = 0 ] ; then
  7858.   MYDIST=`lsb_release -cs`
  7859.   sed 's/$MYDIST/$UPGRADE/' /tmp/meta-backup/myrepo-backup/etc/apt/sources.list
  7860.   sed 's/$MYDIST/$UPGRADE/' /tmp/meta-backup/myrepo-backup/etc/apt/sources.list.d/*
  7861. fi                                          ## end dist upgrade feature
  7862.   DEPS=`aptitude search -F %p ~i --disable-columns | sed 's/$/,/' | tr '\n\r' ' ' | sed 's/, $//'`  ## get list of inst. packages to fill DEPS variable
  7863.                                             ## create the control file for the meta-backup
  7864. echo "Section: misc
  7865. Priority: optional
  7866. Package: my-meta-backup
  7867. Version: 2.1
  7868. Maintainer: meta-backup
  7869. Depends: $DEPS
  7870. Architecture: all
  7871. Description: Personal system backup created by meta-backup
  7872. Personal system backup created by meta-backup. This package can be used to install all applications that are installed on the computer where the backup is made. Can be used on all systems using the same base system version as used on the backup machine." >> /tmp/meta-backup/my-meta-backup/DEBIAN/control
  7873. cd /tmp/meta-backup && dpkg --build my-meta-backup                  ## build and save the package(s)
  7874. if [ $? = 0 ] ; then
  7875.     cd /tmp/meta-backup && dpkg --build my-repo-backup
  7876. fi
  7877. ls /tmp/meta-backup/my-meta-backup.deb                          ## finish backup
  7878.   if [ $? = 0 ] ; then
  7879.     ERROR=no
  7880.     else ERROR=yes
  7881.   fi
  7882. ls /tmp/meta-backup/my-repo-backup.deb
  7883.   if [ $? = 0 ] ; then
  7884.     ERROR=no
  7885.   else ERROR=yes
  7886.   fi
  7887. dialog --title "Meta-backup" --inputbox "$DIALOG6" 8 40 2> /tmp/meta-backup/save    ## move the debs to selected location
  7888.     SAVE=`cat /tmp/meta-backup/save`
  7889.     dialog --title "Meta-backup" --infobox "..." 8 40
  7890.     ls $SAVE
  7891.   if [ $? = 0 ] ; then
  7892.     mv /tmp/meta-backup/*.deb $SAVE
  7893.     chmod 777 $SAVE/my-*-backup.deb
  7894.   else
  7895.     mkdir -p $SAVE
  7896.     mv /tmp/meta-backup/*.deb $SAVE
  7897.     chmod -R 777 $SAVE
  7898.   fi
  7899. if [ $ERROR = no ] ; then                               ## Display exit message
  7900.   dialog --title "Meta-backup" --infobox "$DIALOG2" 8 40
  7901.  else
  7902.   dialog --title "Meta-backup" --infobox "$DIALOG3" 8 40
  7903. fi
  7904. rm -rf /tmp/meta-backup                                 ## cleaning up
  7905. }
  7906.  
  7907.  
  7908.  
  7909. ##################################################
  7910. # Automatically inputs aliases here in       #
  7911. # '.bashrc'                  #
  7912. ##################################################
  7913.  
  7914. ###### Usage: mkalias <name> "<command>"
  7915. # Example: mkalias rm "rm -i"
  7916. function mkalias()
  7917. {
  7918.         if [[ $1 && $2 ]]
  7919.         then
  7920.         echo -e "alias $1=\"$2\"" >> ~/.bashrc
  7921.         alias $1=$2
  7922.         fi
  7923. }
  7924.  
  7925.  
  7926.  
  7927. ##################################################
  7928. # Makes directory then moves into it         #
  7929. ##################################################
  7930.  
  7931. function mkcdr() {
  7932.     mkdir -p -v $1
  7933.     cd $1
  7934. }
  7935.  
  7936.  
  7937.  
  7938. function mkdircd()  { mkdir -p "$@" && eval cd "\"\$$#\""; }
  7939.  
  7940.  
  7941.  
  7942. ##################################################
  7943. # Creates an archive from directory      #
  7944. ##################################################
  7945.  
  7946. function mktar() { tar cvf  "${1%%/}.tar"     "${1%%/}/"; }
  7947.  
  7948.  
  7949.  
  7950. function mktbz() { tar cvjf "${1%%/}.tar.bz2" "${1%%/}/"; }
  7951.  
  7952.  
  7953.  
  7954. function mktgz() { tar cvzf "${1%%/}.tar.gz"  "${1%%/}/"; }
  7955.  
  7956.  
  7957.  
  7958. ##################################################
  7959. # Reminder / to do list              #
  7960. ##################################################
  7961.  
  7962. function mnote()
  7963. {
  7964.     echo -e "- $* \n" >> ~/todo
  7965.     echo -e "- $* \n" >> ~/todo.perm
  7966.     ~/motd.pl
  7967. }
  7968.  
  7969.  
  7970.  
  7971. ##################################################
  7972. # Morse code encoding and decoding       #
  7973. ##################################################
  7974.  
  7975. ###### this is a short Morse code decoder written as a shellscript using sed
  7976. # the Morse coded text should be written with spaces between the letters
  7977. # only good to convert from Morse code to text
  7978. # by scvalex
  7979. function morse2text()
  7980. {
  7981. echo $1\  | tr . 0 | sed -e {s/0----\ /1/g} -e {s/00---\ /2/g} -e {s/000--\ /3/g} -e {s/000-\ /4/g} -e {s/00000\ /5/g} -e {s/-0000\ /6/g} -e {s/--000\ /7/g} -e {s/---00\ /8/g} -e {s/----0\ /9/g} -e {s/-----\ /0/g} \
  7982.     | sed -e {s/-0-0\ /c/g} -e {s/-000\ /b/g} -e {s/00-0\ /f/g} -e {s/0000\ /h/g} -e {s/0---\ /j/g} -e {s/0-00\ /l/g} -e {s/0--0\ /p/g} -e {s/--0-\ /q/g} -e {s/000-\ /v/g} -e {s/-00-\ /x/g} -e {s/-0--\ /y/g} -e {s/--00\ /z/g} \
  7983.     | sed -e {s/0--\ /w/g} -e {s/-00\ /d/g} -e {s/--0\ /g/g} -e {s/-0-\ /k/g} -e {s/---\ /o/g} -e {s/0-0\ /r/g} -e {s/000\ /s/g} -e {s/00-\ /u/g} \
  7984.     | sed -e {s/0-\ /a/g} -e {s/00\ /i/g} -e {s/--\ /m/g} -e {s/-0\ /n/g} \
  7985.     | sed -e {s/0\ /e/g} -e {s/-\ /t/g}
  7986. }
  7987.  
  7988.  
  7989.  
  7990. function text2morse()
  7991. {
  7992. cat > "/tmp/text2morse.py" <<"End-of-message"
  7993. #!/usr/bin/python
  7994. # short mark, dot or 'dit' (.) = .
  7995. # longer mark, dash or 'dah' (-) = -
  7996. # intra-character gap (between the dots and dashes within a character) = no space
  7997. # short gap (between letters) = single space
  7998. # medium gap (between words) = double space
  7999. import sys
  8000. __author__="Aanand Natarajan"
  8001. # morse code dictionary
  8002. codes = {'1':".----",'2':"..---",'3':"...--",'4':"....-",'5':".....",'6':"-....",'7':"--...",'8':"---..",
  8003. '9':"----.",'0':"-----",'A':".-",'B':"-...",'C':"-.-.",'D':"-..",'E':".",'F':"..-.",'G':"--.",
  8004. 'H':"....",'I':"..",'J':".---",'K':"-.-",'L':".-..",'M':"--",'N':"-.",'O':"---",'P':".--.",
  8005. 'Q':"--.-",'R':".-.",'S':"...",'T':"-",'U':"..-",'V':"...-",'W':".--",'X':"-..-",'Y':"-.--",
  8006. 'Z':"--..",
  8007. # punctuations
  8008. ',':"--..--",'.':".-.-.-",'?':"..--..",';':"-.-.-",':':"---...",'/':"-..-.",
  8009. '-':"-....-","'":".----.",'(':"-.--.",')':"-.--.-",'!':"-.-.--",'&':".-...",
  8010. '=':"-...-",'+':".-.-.",'_':"..--.-",'"':".-..-.",'$':"...-..-",'@':".--.-.",
  8011. # space
  8012. ' ':"|"}
  8013. binary = {'.':'.','-':'-',',':' ','|':'  '}
  8014. def encode(value):
  8015.     """ encodes the value into morse code """
  8016.     morse_value=""
  8017.     value.replace('*', 'X')
  8018.     value.replace('^', 'XX')
  8019.     for c in value:
  8020.        try :
  8021.                morse_value += codes[c.upper()]+','
  8022.        except :
  8023.          print "Unintended character " + c + " omitted"
  8024.     return _get_binary(morse_value)
  8025. def decode(morse_code_value):
  8026.     """ decodes the morse bytes """
  8027.     decoded_value = _decode_binary(morse_code_value)
  8028.     ascii_value=""
  8029.     for v in decoded_value.split(","):
  8030.         ascii_value += _get_key(v)
  8031.     return ascii_value
  8032. def _get_binary(value):
  8033.      binary_value = ""
  8034.      for c in value:
  8035.          binary_value += binary[c]
  8036.      return binary_value
  8037. def _get_key(value):
  8038.      """ returns the key for the given value """
  8039.      for k,v in codes.items():
  8040.          if v == value:
  8041.             return k
  8042.      return ''
  8043. def _decode_binary(binary):
  8044.     dah_replaced = binary.replace('-', '-')
  8045.     dit_replaced = dah_replaced.replace('.', '.')
  8046.     comma_replaced = dit_replaced.replace(' ', ',')
  8047.     zero_replaced = comma_replaced.replace('', '|,')
  8048.     return zero_replaced
  8049. def _do_decode(value):
  8050.     print "Decoded : "+decode(value)
  8051. def _do_encode(value):
  8052.     print "Encoded : "+encode(value)
  8053. if __name__ == "__main__":
  8054.    if len(sys.argv) > 2:
  8055.       if sys.argv[1] == 'd' :
  8056.          print "decoding"
  8057.          _do_decode(sys.argv[2])
  8058.       else:
  8059.          print "encoding"
  8060.          _do_encode(sys.argv[2])
  8061.    elif len(sys.argv) > 1:
  8062.         print "encoding"
  8063.         _do_encode(sys.argv[1])
  8064.    else:
  8065.         print "Usage : "+sys.argv[0]+" [d (decode) |e (encode)] [input string]"
  8066. End-of-message
  8067. chmod +x "/tmp/text2morse.py"
  8068. "/tmp/text2morse.py" "$1"
  8069. rm "/tmp/text2morse.py"
  8070. }
  8071.  
  8072.  
  8073.  
  8074. ##################################################
  8075. # Computes most frequent used words of text file #
  8076. ##################################################
  8077.  
  8078. ###### usage:   most_frequent "file.txt"
  8079. function most_frequent()
  8080. {
  8081. cat "$1" | tr -cs "[:alnum:]" "\n"| tr "[:lower:]" "[:upper:]" | awk '{h[$1]++}END{for (i in h){print h[i]" "i}}'|sort -nr | cat -n | head -n 30
  8082. }
  8083.  
  8084.  
  8085.  
  8086. ##################################################
  8087. # Mount Fat                  #
  8088. ##################################################
  8089.  
  8090. function mount_fat()
  8091. {
  8092.     local _DEF_PATH="/media/tmp1"
  8093.     if [ -n "$2" ];then
  8094.         sudo mount -t vfat -o rw,users,flush,umask=0000 "$1" "$2"
  8095.     else
  8096.         sudo mount -t vfat -o rw,users,flush,umask=0000 "$1" $_DEF_PATH
  8097.     fi
  8098. }
  8099.  
  8100.  
  8101.  
  8102. ##################################################
  8103. # Youtube stuff                  #
  8104. ##################################################
  8105.  
  8106. ###### stream YouTube videos directly to your media player
  8107. function mtube() {
  8108.   video_id=$(curl -s $1 | sed -n "/watch_fullscreen/s;.*\(video_id.\+\)&title.*;\1;p");
  8109.   mplayer -fs $(echo "http://youtube.com/get_video.php?$video_id");
  8110. }
  8111.  
  8112.  
  8113.  
  8114. ###### convert to ogg
  8115. function youtube2ogg() {
  8116.     # copyright 2007 - 2010 Christopher Bratusek
  8117.     ffmpeg -i "$1" -vn "$1".ogg
  8118. }
  8119.  
  8120.  
  8121.  
  8122. ###### play YouTube's first match directly
  8123. function ytplay() { args="$*";mplayer -fs $(youtube-dl -g "http://www.youtube.com$(lynx --source "http://www.youtube.com/results?search_query=${args// /+}&aq=f"|grep -m1 '<a id=.*watch?v=.*title'|cut -d\" -f4)"); }
  8124.  
  8125.  
  8126.  
  8127. ##################################################
  8128. # Query Wikipedia via console over DNS       #
  8129. ##################################################
  8130.  
  8131. function mwiki() { blah=`echo $@ | sed -e 's/ /_/g'`; dig +short txt $blah.wp.dg.cx; }
  8132.  
  8133.  
  8134.  
  8135. ##################################################
  8136. # User friendly ps               #
  8137. ##################################################
  8138.  
  8139. function my_ps() { ps $@ -u $USER -o pid,%cpu,%mem,bsdtime,command ; }
  8140.  
  8141.  
  8142.  
  8143. function pp() { my_ps f | awk '!/awk/ && $0~var' var=${1:-".*"} ; }
  8144.  
  8145.  
  8146.  
  8147. function psaux() {
  8148.     [ $# == 1 ] && ps aux | grep $1
  8149. }
  8150.  
  8151.  
  8152.  
  8153. ##################################################
  8154. # Editor startup, should be transparent for      #
  8155. # different versions                 #
  8156. ##################################################
  8157.  
  8158. # function ned()
  8159. # {   if [[ -n `which neditc` ]] ; then
  8160. #         neditc $@
  8161. #     elif [[ -n `which nedit` ]] ; then
  8162. #         nedit $@ >&/dev/null &
  8163. #     else
  8164. #         echo NEdit does not appear to be on this computer.
  8165. #     fi
  8166. # }
  8167.  
  8168.  
  8169.  
  8170. ##################################################
  8171. # Download all data from Google Ngram Viewer     #
  8172. ##################################################
  8173.  
  8174. function ngramviewerdl()
  8175. {
  8176. wget -qO - http://ngrams.googlelabs.com/datasets | grep -E href='(.+\.zip)' | sed -r "s/.*href='(.+\.zip)'.*/\1/" | uniq | while read line; do `wget $line`; done
  8177. }
  8178.  
  8179.  
  8180.  
  8181. ##################################################
  8182. # Run command detached from terminal and without #
  8183. # output                     #
  8184. ##################################################
  8185.  
  8186. ###### Usage: nh
  8187. function nh() {
  8188.     nohup "$@" &>/dev/null &
  8189. }
  8190.  
  8191.  
  8192.  
  8193. ##################################################
  8194. # Stupid simple note taker           #
  8195. ##################################################
  8196.  
  8197. function note()
  8198. {
  8199.         # if file doesn't exist, create it
  8200.         [ -f $HOME/.notes ] || touch $HOME/.notes
  8201.         # no arguments, print file
  8202.         if [ $# = 0 ]
  8203.         then
  8204.                 cat $HOME/.notes
  8205.         # clear file
  8206.         elif [ $1 = -c ]
  8207.         then
  8208.                 > $HOME/.notes
  8209.         # add all arguments to file
  8210.         else
  8211.                 echo "$@" >> $HOME/.notes
  8212.         fi
  8213. }
  8214.  
  8215.  
  8216.  
  8217. ##################################################
  8218. # Open a new terminal tab in the same directory  #
  8219. # as the current                 #
  8220. ##################################################
  8221.  
  8222. ###### SOURCE => http://pastie.caboo.se/188640
  8223. #    AND => http://justinfrench.com/index.php?id=231
  8224. function nth() {
  8225.   osascript -e "
  8226.  Tell application \"Terminal\"
  8227.    activate
  8228.    tell application \"System Events\" to tell process \"Terminal\" to keystroke \"t\" using command down
  8229.    do script with command \"cd '$(pwd)'; clear\" in selected tab of the front window
  8230.  end tell"
  8231. }
  8232.  
  8233.  
  8234.  
  8235. ##################################################
  8236. # Remove apps with style: nuke it from orbit     #
  8237. ##################################################
  8238.  
  8239. ###### You can't stand programs x, y, and z. Remove all trace of their existence by adding this function to your config. It will remove the cruft, the settings, #and such and such. This function doesn't even give a damn about you trying to remove programs that don't exist: it'll just for loop to the next one on #your hit list.
  8240. function nuke() { if [ $(whoami) != "root" ] ; then for x in $@; do sudo apt-get autoremove --purge $x; done; else for x in $@; do apt-get autoremove --purge $x; done; fi }
  8241.  
  8242.  
  8243.  
  8244.  
  8245. ##################################################
  8246. # Echo the lines of a file preceded by line  #
  8247. # number                     #
  8248. ##################################################
  8249.  
  8250. function numberLines() { perl -pe 's/^/$. /' "$@" ; }
  8251.  
  8252.  
  8253.  
  8254. ##################################################
  8255. # Open a GUI app from CLI            #
  8256. ##################################################
  8257.  
  8258. function open() {
  8259.   $1 >/dev/null 2>&1 &
  8260. }
  8261.  
  8262.  
  8263.  
  8264. ##################################################
  8265. # Display text of ODF document in terminal   #
  8266. ##################################################
  8267.  
  8268. ######   $1 = ODF file
  8269. function o3() { unzip -p "$1" content.xml | o3totxt | utf8tolatin1; }
  8270.  
  8271.  
  8272.  
  8273. ##################################################
  8274. # Ownership Changes { own file user }        #
  8275. ##################################################
  8276.  
  8277. function own() { chown -R "$2":"$2" ${1:-.}; }
  8278.  
  8279.  
  8280.  
  8281. ##################################################
  8282. # Download all installed deb packages from   #
  8283. # official repos currently on system         #
  8284. ##################################################
  8285.  
  8286. function packagelistdl()
  8287. {
  8288. sudo dpkg --get-selections | awk '{ print $1};' | while read package; do apt-cache show "$package"| wget -c 'http://ae.archive.ubuntu.com/ubuntu/'`sed -ne '/^Filename/s/^Filename: //p'`; done
  8289. }
  8290.  
  8291.  
  8292.  
  8293. ##################################################
  8294. # Pacman Search                  #
  8295. ##################################################
  8296.  
  8297. function pacsearch() {
  8298.        echo -e "$(pacman -Ss $@ | sed \
  8299.       -e 's#core/.*#\\033[1;31m&\\033[0;37m#g' \
  8300.       -e 's#extra/.*#\\033[0;32m&\\033[0;37m#g' \
  8301.       -e 's#community/.*#\\033[1;35m&\\033[0;37m#g' \
  8302.       -e 's#^.*/.* [0-9].*#\\033[0;36m&\\033[0;37m#g' )"
  8303. }
  8304.  
  8305.  
  8306.  
  8307. ##################################################
  8308. # Removes duplicate paths            #
  8309. ##################################################
  8310.  
  8311. ###### NOTE: symlinks aren't dereferenced (e.g., using `readlink`) as they may
  8312. # exist for compatibility reasons
  8313. function pathremove() {
  8314.     local IFS=':'
  8315.     local newpath
  8316.     local i
  8317.  
  8318.     for i in ${!2}; do
  8319.         if [ "$i" != "$1" ]; then
  8320.             newpath=${newpath:+$newpath:}$i
  8321.         fi
  8322.     done
  8323.     export $2="$newpath"
  8324. }
  8325.  
  8326.  
  8327.  
  8328. ##################################################
  8329. # Print character classes            #
  8330. ##################################################
  8331.  
  8332. function pcharc() { perl -e 'for (0..255) {$_ = chr($_); print if /['$1']/}' | cat -v; echo; }
  8333.  
  8334.  
  8335.  
  8336. ##################################################
  8337. # Quick plot of numbers on stdin (can also pass  #
  8338. # plot paramaters)               #
  8339. ##################################################
  8340.  
  8341. # requires gnuplot: sudo apt-get install gnuplot
  8342. # example: seq 1000 | sed 's/.*/s(&)/' | bc -l | plot linecolor 2
  8343. function plot() { { echo 'plot "-"' "$@"; cat; } | gnuplot -persist; }
  8344.  
  8345.  
  8346.  
  8347. ##################################################
  8348. # Scans a port, returns what's on it.        #
  8349. ##################################################
  8350.  
  8351. function port() {
  8352. lsof -i :"$1"
  8353. }
  8354.  
  8355.  
  8356.  
  8357. ##################################################
  8358. # Portscan in one line               #
  8359. ##################################################
  8360.  
  8361. function portscan()
  8362. {
  8363. $HOST=127.0.0.1;for((port=1;port<=65535;++port));do echo -en "$port ";if echo -en "open $HOST $port\nlogout\quit" | telnet 2>/dev/null | grep 'Connected to' > /dev/null;then echo -en "\n\nport $port/tcp is open\n\n";fi;done
  8364. }
  8365.  
  8366.  
  8367.  
  8368. ##################################################
  8369. # Find the printer driver (ppd) type being used  #
  8370. ##################################################
  8371.  
  8372. function printdriver() {
  8373.         lpoptions -d $1 | grep -oe "printer-make-and-model='.*'" | cut -f2 -d "=" | sed -r s/\'//g
  8374. }
  8375.  
  8376.  
  8377.  
  8378. ##################################################
  8379. # Print a row of characters across the terminal  #
  8380. ##################################################
  8381.  
  8382. ###### Default character is "=", default color is white
  8383. function println()
  8384. {
  8385. echo -n -e "\e[038;05;${2:-255}m";printf "%$(tput cols)s"|sed "s/ /${1:-=}/g"
  8386. }
  8387.  
  8388.  
  8389.  
  8390. ##################################################
  8391. # Run program on a timer             #
  8392. ##################################################
  8393.  
  8394. ###### Example: program-timer 20 viewnior arg1
  8395. function program-timer() { perl -e 'alarm shift; exec @ARGV' "$@" & exit; }
  8396.  
  8397.  
  8398.  
  8399. ##################################################
  8400. # Progress visuals               #
  8401. ##################################################
  8402.  
  8403. function progressbar()
  8404. # copyright 2007 - 2010 Christopher Bratusek
  8405. {
  8406.     SP_COLOUR="\e[37;44m"
  8407.     SP_WIDTH=5.5
  8408.     SP_DELAY=0.2
  8409.     SP_STRING=${2:-"'|/=\'"}
  8410.     while [ -d /proc/$1 ]
  8411.     do
  8412.         printf "$SP_COLOUR\e7  %${SP_WIDTH}s  \e8\e[01;37m" "$SP_STRING"
  8413.         sleep ${SP_DELAY:-.2}
  8414.         SP_STRING=${SP_STRING#"${SP_STRING%?}"}${SP_STRING%?}
  8415.     done
  8416.     tput sgr0
  8417. }
  8418.  
  8419.  
  8420.  
  8421. ###### please wait...
  8422. # copyright 2007 - 2010 Christopher Bratusek
  8423. function spanner() {
  8424.     PROC=$1;COUNT=0
  8425.     echo -n "Please wait "
  8426.     while [ -d /proc/$PROC ];do
  8427.         while [ "$COUNT" -lt 10 ];do
  8428.             echo -ne '\x08  ' ; sleep 0.1
  8429.             ((COUNT++))
  8430.         done
  8431.         until [ "$COUNT" -eq 0 ];do
  8432.             echo -ne '\x08\x08 ' ; sleep 0.1
  8433.             ((COUNT -= 1))
  8434.         done
  8435.     done
  8436. }
  8437.  
  8438.  
  8439.  
  8440. function spin() {
  8441.     # copyright 2007 - 2010 Christopher Bratusek
  8442.        echo -n "|/     |"
  8443.        while [ -d /proc/$1 ]
  8444.        do
  8445.        # moving right
  8446.        echo -ne "\b\b\b\b\b\b\b-     |"
  8447.        sleep .05
  8448.        echo -ne "\b\b\b\b\b\b\b\\     |"
  8449.        sleep .05
  8450.        echo -ne "\b\b\b\b\b\b\b|     |"
  8451.        sleep .05
  8452.        echo -ne "\b\b\b\b\b\b\b /    |"
  8453.        sleep .05
  8454.        echo -ne "\b\b\b\b\b\b-    |"
  8455.        sleep .05
  8456.        echo -ne "\b\b\b\b\b\b\\    |"
  8457.        sleep .05
  8458.        echo -ne "\b\b\b\b\b\b|    |"
  8459.        sleep .05
  8460.        echo -ne "\b\b\b\b\b\b /   |"
  8461.        sleep .05
  8462.        echo -ne "\b\b\b\b\b-   |"
  8463.        sleep .05
  8464.        echo -ne "\b\b\b\b\b\\   |"
  8465.        sleep .05
  8466.        echo -ne "\b\b\b\b\b|   |"
  8467.        sleep .05
  8468.        echo -ne "\b\b\b\b\b /  |"
  8469.        sleep .05
  8470.        echo -ne "\b\b\b\b-  |"
  8471.        sleep .05
  8472.        echo -ne "\b\b\b\b\\  |"
  8473.        sleep .05
  8474.        echo -ne "\b\b\b\b|  |"
  8475.        sleep .05
  8476.        echo -ne "\b\b\b\b / |"
  8477.        sleep .05
  8478.        echo -ne "\b\b\b- |"
  8479.        sleep .05
  8480.        echo -ne "\b\b\b\\ |"
  8481.        sleep .05
  8482.        echo -ne "\b\b\b| |"
  8483.        sleep .05
  8484.        echo -ne "\b\b\b /|"
  8485.        sleep .05
  8486.        echo -ne "\b\b-|"
  8487.        sleep .05
  8488.        echo -ne "\b\b\\|"
  8489.        sleep .05
  8490.        echo -ne "\b\b||"
  8491.        sleep .05
  8492.        echo -ne "\b\b/|"
  8493.        sleep .05
  8494.        # moving left
  8495.        echo -ne "\b\b||"
  8496.        sleep .05
  8497.        echo -ne "\b\b\\|"
  8498.        sleep .05
  8499.        echo -ne "\b\b-|"
  8500.        sleep .05
  8501.        echo -ne "\b\b\b/ |"
  8502.        sleep .05
  8503.        echo -ne "\b\b\b| |"
  8504.        sleep .05
  8505.        echo -ne "\b\b\b\\ |"
  8506.        sleep .05
  8507.        echo -ne "\b\b\b- |"
  8508.        sleep .05
  8509.        echo -ne "\b\b\b\b/  |"
  8510.        sleep .05
  8511.        echo -ne "\b\b\b\b|  |"
  8512.        sleep .05
  8513.        echo -ne "\b\b\b\b\\  |"
  8514.        sleep .05
  8515.        echo -ne "\b\b\b\b-  |"
  8516.        sleep .05
  8517.        echo -ne "\b\b\b\b\b/   |"
  8518.        sleep .05
  8519.        echo -ne "\b\b\b\b\b|   |"
  8520.        sleep .05
  8521.        echo -ne "\b\b\b\b\b\\   |"
  8522.        sleep .05
  8523.        echo -ne "\b\b\b\b\b-   |"
  8524.        sleep .05
  8525.        echo -ne "\b\b\b\b\b\b/    |"
  8526.        sleep .05
  8527.        echo -ne "\b\b\b\b\b\b|    |"
  8528.        sleep .05
  8529.        echo -ne "\b\b\b\b\b\b\\    |"
  8530.        sleep .05
  8531.        echo -ne "\b\b\b\b\b\b-    |"
  8532.        sleep .05
  8533.        echo -ne "\b\b\b\b\b\b\b/     |"
  8534.        sleep .05
  8535.        done
  8536.     echo -e "\b\b\b\b\b\b\b\b\b|=======| done!"
  8537. }
  8538.  
  8539.  
  8540.  
  8541. function spinner()
  8542. # copyright 2007 - 2010 Christopher Bratusek
  8543. {
  8544.     PROC=$1
  8545.     while [ -d /proc/$PROC ];do
  8546.         echo -ne '\e[01;32m/\x08' ; sleep 0.05
  8547.         echo -ne '\e[01;32m-\x08' ; sleep 0.05
  8548.         echo -ne '\e[01;32m\\\x08' ; sleep 0.05
  8549.         echo -ne '\e[01;32m|\x08' ; sleep 0.05
  8550.     done
  8551. }
  8552.  
  8553.  
  8554.  
  8555. ###### Display a progress process
  8556. # To start the spinner2 function, you have to send the function
  8557. # into the background. To stop the spinner2 function, you have
  8558. # to define the argument "stop".
  8559. # EXAMPLE:
  8560. #    echo -n "Starting some daemon "; spinner2 &
  8561. #    if sleep 10; then
  8562. #       spinner2 "stop"; echo -e "\t[ OK ]"
  8563. #    else
  8564. #       spinner2 "stop"; echo -e "\t[ FAILED ]"
  8565. #    fi
  8566. function spinner2() {
  8567.      local action=${1:-"start"}
  8568.      declare -a sign=( "-" "/" "|" "\\\\" )
  8569.       # define singnal file...
  8570.       [ "$action" = "start" ] && echo 1 > /tmp/signal
  8571.       [ "$action" = "stop" ] && echo 0 > /tmp/signal
  8572.       while [ "$( cat /tmp/signal 2>/dev/null )" == "1" ] ; do
  8573.           for (( i=0; i<${#sign[@]}; i++ )); do
  8574.               echo -en "${sign[$i]}\b"
  8575.               # with this command you can use millisecond as sleep time - perl rules ;-)
  8576.               perl -e 'select( undef, undef, undef, 0.1 );'
  8577.           done
  8578.       done
  8579.       # clear the last ${sign[$i]} sign at finish...
  8580.       [ "$action" = "stop" ] && echo -ne " \b"
  8581. }
  8582.  
  8583.  
  8584.  
  8585. function working()
  8586. # copyright 2007 - 2010 Christopher Bratusek
  8587. {
  8588.    while [ -d /proc/$1 ]
  8589.    do
  8590.     echo -ne "w      \b\b\b\b\b\b\b";sleep .08;
  8591.     echo -ne "wo     \b\b\b\b\b\b\b";sleep .08;
  8592.     echo -ne "wor    \b\b\b\b\b\b\b";sleep .08;
  8593.     echo -ne "work   \b\b\b\b\b\b\b";sleep .08;
  8594.     echo -ne "worki  \b\b\b\b\b\b\b";sleep .08;
  8595.     echo -ne "workin \b\b\b\b\b\b\b";sleep .08;
  8596.     echo -ne "working\b\b\b\b\b\b\b";sleep .08;
  8597.     echo -ne " orking\b\b\b\b\b\b\b";sleep .08;
  8598.     echo -ne "  rking\b\b\b\b\b\b\b";sleep .08;
  8599.     echo -ne "   king\b\b\b\b\b\b\b";sleep .08;
  8600.     echo -ne "    ing\b\b\b\b\b\b\b";sleep .08;
  8601.     echo -ne "     ng\b\b\b\b\b\b\b";sleep .08;
  8602.     echo -ne "      g\b\b\b\b\b\b\b";sleep .08;
  8603.    done
  8604. }
  8605.  
  8606.  
  8607.  
  8608. ##################################################
  8609. # Pronounce an English word          #
  8610. ##################################################
  8611.  
  8612. ###### usage:   pronounce "word1" "word2" "word3" "..."
  8613. function pronounce() { for a in $@; do wget -qO- $(wget -qO- "http://www.m-w.com/dictionary/$a" | grep 'return au' | sed -r "s|.*return au\('([^']*)', '([^'])[^']*'\).*|http://cougar.eb.com/soundc11/\2/\1|") | aplay -q; done }
  8614.  
  8615.  
  8616.  
  8617. ###### usage:   pronounce_ "word1" "word2" "word3" "..."
  8618. # requires 'mpg123' - sudo apt-get install mp321, but better dictionary
  8619. function pronounce_() { wget -qO- $(wget -qO- "http://dictionary.reference.com/browse/$@" | grep 'soundUrl' | head -n 1 | sed 's|.*soundUrl=\([^&]*\)&.*|\1|' | sed 's/%3A/:/g;s/%2F/\//g') | mpg123 -; }
  8620.  
  8621.  
  8622.  
  8623. ##################################################
  8624. # Pull a single file out of a .tar.gz        #
  8625. ##################################################
  8626.  
  8627. function pullout() {
  8628.   if [ $# -ne 2 ]; then
  8629.     echo "need proper arguments:"
  8630.     echo "pullout [file] [archive.tar.gz]"
  8631.     return 1
  8632.   fi
  8633.   case $2 in
  8634.     *.tar.gz|*.tgz)
  8635.     gunzip < $2 | tar -xf - $1
  8636.     ;;
  8637.     *)
  8638.     echo $2 is not a valid archive
  8639.     return 1
  8640.     ;;
  8641.   esac
  8642.   return 0
  8643. }
  8644.  
  8645.  
  8646.  
  8647. ##################################################
  8648. # Create QR codes from a URL             #
  8649. ##################################################
  8650.  
  8651. function qrurl() { curl -sS "http://chart.apis.google.com/chart?chs=200x200&cht=qr&chld=H|0&chl=$1" -o - | display -filter point -resize 600x600 png:-; }
  8652.  
  8653.  
  8654.  
  8655. ##################################################
  8656. # Turning on and off Internet radio      #
  8657. ##################################################
  8658.  
  8659. function radio() { if [ "$(pidof mpg123)" ] ; then killall mpg123; else mpg123 -q -@ http://173.236.29.51:8200 & fi }
  8660.  
  8661.  
  8662.  
  8663. ##################################################
  8664. # Scroll file one line at a time (w/only UNIX    #
  8665. # base tools)                    #
  8666. ##################################################
  8667.  
  8668. ###### usage:   rd < file ; or ... | rd
  8669. function rd_() { IFS='<ctrl-m>';$@;for i in `sed 's.\\\.\\\134.g;s.%.\\\045.g'`;do printf "$i$IFS";sleep 1;done ; }
  8670.  
  8671.  
  8672.  
  8673. ##################################################
  8674. # Copy Remastersys backups to '~/Backups'    #
  8675. # folder (only after Remastersys has backed-up   #
  8676. # something)                     #
  8677. ##################################################
  8678.  
  8679. function remastersys-copy()
  8680. {
  8681.     notify-send -t 3000 -i /usr/share/icons/gnome/32x32/status/info.png "Remastersys ISO Copy Started"
  8682.     DISTRIB_ID=`cat /etc/lsb-release | grep DISTRIB_ID | cut -d '=' -f 2`
  8683.     DISTRIB_CODENAME=`cat /etc/lsb-release | grep DISTRIB_CODENAME | cut -d '=' -f 2`
  8684.     mkdir "/home/$USER/Backups"
  8685.     mkdir "/home/$USER/Backups/$DISTRIB_ID $DISTRIB_CODENAME Backup `date +-%e-%m-%Y`"
  8686.     cd "/home/$USER/Backups/$DISTRIB_ID $DISTRIB_CODENAME Backup `date +-%e-%m-%Y`"
  8687.     echo 'Password:     password' >> Password.txt
  8688.     cp /home/remastersys/remastersys/custombackup.iso "/home/$USER/Backups/$DISTRIB_ID $DISTRIB_CODENAME Backup `date +-%e-%m-%Y`"
  8689.     cd "/home/$USER/Backups/"
  8690.     rename 's/\b([a-z])/\u$1/g' "$DISTRIB_ID $DISTRIB_CODENAME Backup `date +-%e-%m-%Y`"
  8691.     notify-send -t 3000 -i /usr/share/icons/gnome/32x32/status/info.png "Remastersys ISO Copy Finished" ;
  8692. }
  8693.  
  8694.  
  8695.  
  8696. ##################################################
  8697. # Reminder for whatever whenever         #
  8698. ##################################################
  8699.  
  8700. function remindme()
  8701. {
  8702. sleep $1 && zenity --info --text "$2" &
  8703. }
  8704.  
  8705.  
  8706.  
  8707. ##################################################
  8708. # Remount a device               #
  8709. ##################################################
  8710.  
  8711. function remount() {
  8712.     # copyright 2007 - 2010 Christopher Bratusek
  8713.     DEVICE=$1
  8714.     shift
  8715.     mount -oremount,$@ $DEVICE
  8716. }
  8717.  
  8718.  
  8719.  
  8720. ##################################################
  8721. # Repeats a command every x seconds      #
  8722. ##################################################
  8723.  
  8724. ###### Usage: repeat PERIOD COMMAND
  8725. function repeat() {
  8726.     local period
  8727.     period=$1; shift;
  8728.     while (true); do
  8729.         eval "$@";
  8730.     sleep $period;
  8731.     done
  8732. }
  8733.  
  8734.  
  8735.  
  8736. ##################################################
  8737. # Add repo                   #
  8738. ##################################################
  8739.  
  8740. function repoadd() {
  8741.     # copyright 2007 - 2010 Christopher Bratusek
  8742.     reprepro -Vb "$REPO_HOME" include "$REPO_DIST" *.changes
  8743.     cd "$REPO_HOME"/dists/"$REPO_DIST"
  8744.     gpg -abs -o Release.gpg Release
  8745. }
  8746.  
  8747.  
  8748.  
  8749. ##################################################
  8750. # Set permissions to "standard" values (644/755),#
  8751. # recursive                  #
  8752. ##################################################
  8753.  
  8754. ###### Usage: resetp
  8755. function resetp() {
  8756.     chmod -R u=rwX,go=rX "$@"
  8757. }
  8758.  
  8759.  
  8760.  
  8761. ##################################################
  8762. # X DISPLAY functions                #
  8763. ##################################################
  8764.  
  8765. function reset_display()
  8766. {
  8767.     if [ "$SHLVL" -eq 1 ]; then
  8768.         echo $DISPLAY > $HOME/.display
  8769.     else
  8770.         if [ -e $HOME/.display ]; then
  8771.             export DISPLAY=$(cat $HOME/.display)
  8772.         fi
  8773.     fi
  8774. }
  8775.  
  8776.  
  8777.  
  8778. function set_xtitle()
  8779. {
  8780.     if [ $TERM == "xterm" ]; then
  8781.         echo -ne "\033]0;${USER}@${HOSTNAME}: ${PWD}\007"
  8782.     fi
  8783. }
  8784. # if [ "$UID" -ne 0 ]; then
  8785. #     reset_display
  8786. # fi
  8787.  
  8788.  
  8789.  
  8790. ##################################################
  8791. # Daemon management              #
  8792. ##################################################
  8793.  
  8794. # function restart() { sudo /etc/rc.d/$1 restart; }
  8795.  
  8796.  
  8797.  
  8798. # function start() { sudo /etc/rc.d/$1 start; }
  8799.  
  8800.  
  8801.  
  8802. # function stop() { sudo /etc/rc.d/$1 stop; }
  8803.  
  8804.  
  8805.  
  8806. ##################################################
  8807. # Restart the windows, only once         #
  8808. ##################################################
  8809.  
  8810. function restowin() { sudo grub-set-default 3 && sudo reboot; }
  8811.  
  8812.  
  8813.  
  8814. ##################################################
  8815. # Rip a file with handbrake and good options     #
  8816. ##################################################
  8817.  
  8818. function rip() {
  8819. handbrake -i /dev/dvd -o ${HOME}/Movies/${1}.mp4 -L -U -F -f mp4 -e x264 -b 4000 -B 192
  8820. }
  8821.  
  8822.  
  8823.  
  8824. ##################################################
  8825. # Remove an inode via inode number       #
  8826. ##################################################
  8827.  
  8828. function rminode() {
  8829.         find . -inum $1 -exec rm -i {} \;
  8830. }
  8831.  
  8832.  
  8833.  
  8834. ##################################################
  8835. # Roll - archive wrapper             #
  8836. ##################################################
  8837.  
  8838. ###### usage: roll <foo.tar.gz> ./foo ./bar
  8839. function roll()
  8840. {
  8841.   FILE=$1
  8842.   case $FILE in
  8843.     *.tar.bz2) shift && tar cjf $FILE $* ;;
  8844.     *.tar.gz) shift && tar czf $FILE $* ;;
  8845.     *.tgz) shift && tar czf $FILE $* ;;
  8846.     *.zip) shift && zip $FILE $* ;;
  8847.     *.rar) shift && rar $FILE $* ;;
  8848.   esac
  8849. }
  8850.  
  8851.  
  8852.  
  8853. ##################################################
  8854. # Removing all extended attributes from a    #
  8855. # directory tree                 #
  8856. ##################################################
  8857.  
  8858. function rr()
  8859. {
  8860.     for i in $(ls -Rl@ | grep '^    ' | awk '{print $1}' | sort -u); \
  8861.        do echo Removing $i ... >&2;  \
  8862.        find . | xargs xattr -d $i 2>/dev/null ; done
  8863. }
  8864.  
  8865.  
  8866.  
  8867. ##################################################
  8868. # RTFM function                  #
  8869. ##################################################
  8870.  
  8871. function rtfm() { help $@ || man $@ || $BROWSER "http://www.google.com/search?q=$@"; }
  8872.  
  8873.  
  8874.  
  8875. ##################################################
  8876. # Make a backup before editing a file        #
  8877. ##################################################
  8878.  
  8879. function safeedit() {
  8880. cp $1 ${1}.backup && vim $1
  8881. }
  8882.  
  8883.  
  8884.  
  8885. ##################################################
  8886. # Sanitize - set file/directory owner and    #
  8887. # permissions to normal values (644/755)     #
  8888. ##################################################
  8889.  
  8890. ###### usage: sanitize <file>
  8891. function sanitize()
  8892. {
  8893.   chmod -R u=rwX,go=rX "$@"
  8894.   chown -R ${USER}:users "$@"
  8895. }
  8896.  
  8897.  
  8898.  
  8899. ##################################################
  8900. # Save a specified directory             #
  8901. ##################################################
  8902.  
  8903. function save() { /usr/bin/sed "/$@/d" ~/.dirs > ~/.dirs1; \mv ~/.dirs1 ~/.dirs; echo "$@"=\"`pwd`\" >> ~/.dirs; source ~/.dirs ; }
  8904.  
  8905.  
  8906.  
  8907. ##################################################
  8908. # Save a file to ~/Temp              #
  8909. ##################################################
  8910.  
  8911. function saveit() {
  8912. cp $1 ${HOME}/Temp/${1}.saved
  8913. }
  8914.  
  8915.  
  8916.  
  8917. ##################################################
  8918. # Screencasting with mplayer webcam window   #
  8919. ##################################################
  8920.  
  8921. function screencastw()
  8922. {
  8923. mplayer -cache 128 -tv driver=v4l2:width=176:height=177 -vo xv tv:// -noborder -geometry "95%:93%" -ontop | ffmpeg -y -f alsa -ac 2 -i pulse -f x11grab -r 30 -s `xdpyinfo | grep 'dimensions:'|awk '{print $2}'` -i :0.0 -acodec pcm_s16le output.wav -an -vcodec libx264 -vpre lossless_ultrafast -threads 0 output.mp4
  8924. }
  8925.  
  8926.  
  8927.  
  8928. ##################################################
  8929. # Search package database            #
  8930. ##################################################
  8931.  
  8932. ###### search Gentoo package database (portage) using eix
  8933. #   $1 = search term (package name)
  8934. # function sd() { eix -FsSc "$1"; }  # Search all available w/ desc.; show summary
  8935.  
  8936.  
  8937.  
  8938. # function se() { eix -F "^$1\$"; }  # Search exact available; show details
  8939.  
  8940.  
  8941.  
  8942. # function si() { eix -FIc "$1"; }   # Search installed; show summary
  8943.  
  8944.  
  8945.  
  8946. # function sp() { eix -Fc "$1"; }     # Search all available; show summary
  8947.  
  8948.  
  8949.  
  8950. ###### search Arch package database using pacman
  8951. #   $1 = search term (package name
  8952. # function sp() {
  8953. #    echo -e "$(pacman -Ss "$@" | sed \
  8954. #        -e 's#^core/.*#\\033[1;31m&\\033[0;37m#g' \
  8955. #        -e 's#^extra/.*#\\033[0;32m&\\033[0;37m#g' \
  8956. #        -e 's#^community/.*#\\033[1;35m&\\033[0;37m#g' \
  8957. #        -e 's#^.*/.* [0-9].*#\\033[0;36m&\\033[0;37m#g' ) \
  8958. #        \033[0m"
  8959. # }
  8960.  
  8961.  
  8962.  
  8963. ###### search Debian (or Ubuntu) package database (apt) using dpkg
  8964. #   $1 = search term (package name)
  8965. function sp() { apt-cache search "$1" | grep -i "$1"; }  # search all available
  8966.  
  8967.  
  8968.  
  8969. ##################################################
  8970. # Search and replace words/phrases from text file#
  8971. ##################################################
  8972.  
  8973. ###### usage:   searchnreplace "whatever oldtext" "whatever newtext" "file(s) to act on"
  8974. function searchnreplace()
  8975. {
  8976. # Store old text and new text in variables
  8977. old=$1;
  8978. new=$2;
  8979. # Shift positional parameters to places to left (get rid of old and
  8980. # new from command line)
  8981. shift;
  8982. shift;
  8983. # Store list of files as a variable
  8984. files=$@;
  8985. a='';
  8986. for a in $files
  8987.  do
  8988.   temp=$(echo "/tmp/$LOGNAME-$a");
  8989. # echo "$temp";
  8990.   echo -n ".";
  8991.   sed -e "s/$old/$new/g" $a > $temp;
  8992.   mv $temp $a;
  8993.  done
  8994. echo;
  8995. echo -e "Searched $# files for '$old' and replaced with '$new'";
  8996. }
  8997.  
  8998.  
  8999.  
  9000. ##################################################
  9001. # Auto send an attachment from CLI       #
  9002. ##################################################
  9003.  
  9004. function send() {
  9005. echo "File auto-sent from linux." | mutt -s "See Attached File" -a $1 $2
  9006. }
  9007.  
  9008.  
  9009.  
  9010. ##################################################
  9011. # Manage services                #
  9012. ##################################################
  9013.  
  9014. function service() {
  9015.   if [ $# -lt 2 ]; then
  9016.     echo "Missing service name or command"
  9017.     return 1
  9018.   fi
  9019.   sudo /etc/init.d/$1 $2 && return 0
  9020. }
  9021.  
  9022.  
  9023.  
  9024. ###### service() { /etc/rc.d/$1 $2; }
  9025. function service_() {
  9026.         if [ -n "$2"  ]
  9027.         then
  9028.                 /etc/rc.d/$1 $2
  9029.         else
  9030.                 echo    "All daemons"
  9031.                 ls --ignore=functions* /etc/rc.d/
  9032.                 echo    "Running daemons"
  9033.                 ls /var/run/daemons
  9034.         fi
  9035. }
  9036.  
  9037.  
  9038.  
  9039. ##################################################
  9040. # Pseudo namespaces in bash          #
  9041. ##################################################
  9042.  
  9043. ## copyright: 2009, Poor Yorick
  9044. ## author url:  http://www.pooryorick.com
  9045. ## license: http://www.ynform.org/w/Pub/OpenSourceSharewareLicense
  9046. ## to "import" functions and assign them to pseudo namespaces using prefixes
  9047. ## caveat: works well for functions, but there is still only one global namespace -- no script-level namespace like Python's
  9048. # function shimport() {
  9049. #   local magic part prefix script script2 t tvar var vartype
  9050. #   magic=__shimport__
  9051. #   script='
  9052. #   { @1 ; } >&2
  9053. #   @script2
  9054. #   '
  9055. #   script="${script//@1/$(< /dev/stdin)}"
  9056. #   script=$(printf '%s\n%s' "$script" "declare -p $magic")
  9057. #   prefix="$1"
  9058. #   shift
  9059. #   script2=''
  9060. #   while test ${#@} -gt 0; do
  9061. #       var=${1%%=*}
  9062. #       vartype=${1#*=}
  9063. #       case "$vartype" in
  9064. #           f*)
  9065. #               t=-f
  9066. #               ;;
  9067. #           v*)
  9068. #               t=-p
  9069. #               ;;
  9070. #           *)
  9071. #               echo "$vartype" is an invalid type specifier for "$var"!
  9072. #               return 1
  9073. #               ;;
  9074. #       esac
  9075. #       read -d '' part <<-'EOF'
  9076. #           @magic=$(declare @t @var)
  9077. #           @magic=${@magic/@var/@prefix@var}
  9078. #           printf '%s\\n' "$@magic"
  9079. #       EOF
  9080. #       for tvar in magic t var prefix; do
  9081. #           part=${part//@$tvar/${!tvar}}
  9082. #       done
  9083. #       script2="$(printf '%s\n%s\n' "$script2" "$part")"
  9084. #       shift
  9085. #   done
  9086. #   printf '%s\n' "$(bash -c "${script//@script2/$script2}")"
  9087. # }
  9088. # shimport_test1=$(cat <<-'EOG'
  9089. #   eval "$(shimport mod1_ var1=v var2=v func1=f <<-'EOF'
  9090. #       echo welcome to the inner script!
  9091. #       var1=( one two "forty three" )
  9092. #       var2=val2
  9093. #       function func1() {
  9094. #           echo welcome to func1!
  9095. #       }
  9096. #       EOF
  9097. #   )"
  9098. #   mod1_func1
  9099. #   printf 'mod1_var1: %s\n' "${mod1_var1[@]}"
  9100. # EOG
  9101. # )
  9102. # eval "$shimport_test1"
  9103. #    }}}
  9104.  
  9105.  
  9106.  
  9107. ##################################################
  9108. # Shot - takes a screenshot of your current  #
  9109. # window                     #
  9110. ##################################################
  9111.  
  9112. function shot()
  9113. {
  9114. import -frame -strip -quality 75 "$HOME/$(date +%s).png"
  9115. }
  9116.  
  9117.  
  9118.  
  9119. ##################################################
  9120. # Create an easy to pronounce shortened URL from #
  9121. # CLI                        #
  9122. ##################################################
  9123.  
  9124. function shout() { curl -s "http://shoutkey.com/new?url=$1" | sed -n 's/\<h1\>/\&/p' | sed 's/<[^>]*>//g;/</N;//b' ;}
  9125.  
  9126.  
  9127.  
  9128. ##################################################
  9129. # To remind yourself of an alias (given some     #
  9130. # part of it)                    #
  9131. ##################################################
  9132.  
  9133. function showa() { /usr/bin/grep -i -a1 $@ ~/.aliases.bash | grep -v '^\s*$' ; }
  9134.  
  9135.  
  9136.  
  9137. ##################################################
  9138. # Show the contents of a file, including     #
  9139. # additional useful info             #
  9140. ##################################################
  9141.  
  9142. function showfile()
  9143. {
  9144. width=72
  9145. for input
  9146. do
  9147.   lines="$(wc -l < $input | sed 's/ //g')"
  9148.   chars="$(wc -c < $input | sed 's/ //g')"
  9149.   owner="$(ls -ld $input | awk '{print $3}')"
  9150.   echo "-----------------------------------------------------------------"
  9151.   echo "File $input ($lines lines, $chars characters, owned by $owner):"
  9152.   echo "-----------------------------------------------------------------"
  9153.   while read line
  9154.     do
  9155.       if [ ${#line} -gt $width ] ; then
  9156.         echo "$line" | fmt | sed -e '1s/^/  /' -e '2,$s/^/+ /'
  9157.       else
  9158.         echo "  $line"
  9159.       fi
  9160.     done < $input
  9161.   echo "-----------------------------------------------------------------"
  9162. done | more
  9163. }
  9164.  
  9165.  
  9166.  
  9167. ##################################################
  9168. # ShowTimes: show the modification, metadata-    #
  9169. # change, and access times of a file         #
  9170. ##################################################
  9171.  
  9172. function showTimes() { stat -f "%N:   %m %c %a" "$@" ; }
  9173.  
  9174.  
  9175.  
  9176. ##################################################
  9177. # Used by file                   #
  9178. ##################################################
  9179.  
  9180. function sh_coloroff()
  9181. {
  9182. echo -en "$reset_color"
  9183. }
  9184.  
  9185.  
  9186.  
  9187. function sh_colormsg()
  9188. {
  9189. [ -n "$1" ] && echo -en "${fg_bold}${@}${reset_color}"
  9190. }
  9191.  
  9192.  
  9193.  
  9194. function sh_error()
  9195. {
  9196. echo -e "${fg_bold}[ e ]${reset_color} $@"
  9197. }
  9198.  
  9199.  
  9200.  
  9201. function sh_info()
  9202. {
  9203. echo -e "${fg_bold}[ i ]${reset_color} $@"
  9204. }
  9205.  
  9206.  
  9207.  
  9208. function sh_success()
  9209. {
  9210. echo -e "${fg_bold}[ k ]${reset_color} $@"
  9211. }
  9212.  
  9213.  
  9214.  
  9215. function sh_mesg()
  9216. {
  9217. echo -e "${fg_bold}[ m ]${reset_color} $@"
  9218. }
  9219.  
  9220.  
  9221.  
  9222. ###### use with   svn diff -r `sh_svnprev`
  9223. function sh_svnprev()
  9224. { echo $(( `svnversion . | sed 's/[^0-9].*//'` - 1))
  9225. }
  9226.  
  9227.  
  9228.  
  9229. ###### $1 - path
  9230. function sh_fcore()
  9231. {
  9232.   p="."
  9233.   [ -n "$1" ] && p="$1"
  9234.   find $p -name "core\.*[[:digit:]]*" -type f 2>& /dev/null
  9235.   return 0
  9236. }
  9237.  
  9238.  
  9239.  
  9240. ##################################################
  9241. # Ssh functions                  #
  9242. ##################################################
  9243.  
  9244. function slak()
  9245. {
  9246.     if [ $# -lt 2 ]; then
  9247.         echo "add public key to securelink server"
  9248.         echo "usage: skak [accountname] [sl port]"
  9249.     else
  9250.         cat /Volumes/Library/ssh/id_rsa-$1.pub | ssh -q lila@localhost -p $2 "if [ ! -d ~/.ssh/ ] ; then mkdir ~/.ssh ; fi ; chmod 700 ~/.ssh/ ; cat - >> ~/.ssh/authorized_keys ; chmod 600 ~/.ssh/authorized_keys"
  9251.     fi
  9252. }
  9253.  
  9254.  
  9255.  
  9256. function slssh()
  9257. {
  9258.     if [ $# -lt 1 ]; then
  9259.         echo "connect to securelink ssh session"
  9260.         echo "usage slssh [port#]"
  9261.         echo "ssh -p \$1 localhost"
  9262.     else
  9263.         ssh -p $1 localhost
  9264.     fi
  9265. }
  9266.  
  9267.  
  9268.  
  9269. function slpg()
  9270. {
  9271.     if [ $# -lt 1 ]; then
  9272.         echo "create securelink ssh tunnel for postgres"
  9273.         echo "usage: slpg [port#]"
  9274.         echo "ssh -N localhost -L 2345/localhost/5432 -p \$1"
  9275.     else
  9276.         ssh -N localhost -L 2345/localhost/5432 -p $1
  9277.     fi
  9278. }
  9279.  
  9280.  
  9281.  
  9282. function sshpg()
  9283. {
  9284.     if [ $# -lt 1 ]; then
  9285.         echo "create ssh tunnel for postgres"
  9286.         echo "usage: sshpg username@server"
  9287.         echo "ssh -N \$1 -L 2345/localhost/5432"
  9288.     else
  9289.         ssh -N $1 -L 2345/localhost/5432
  9290.     fi
  9291. }
  9292.  
  9293.  
  9294.  
  9295. function sshpg2()
  9296. {
  9297.     if [ $# -lt 1 ]; then
  9298.         echo "create ssh tunnel for postgres"
  9299.         echo "usage: sshpg username@server"
  9300.         echo "ssh -N \$1 -L \$2/localhost/5432"
  9301.     else
  9302.         ssh -N $1 -L $2/localhost/5432
  9303.     fi
  9304. }
  9305.  
  9306.  
  9307.  
  9308. ##################################################
  9309. # Function that outputs dots every second until  #
  9310. # command completes              #
  9311. ##################################################
  9312.  
  9313. function sleeper() { while `ps -p $1 &>/dev/null`; do echo -n "${2:-.}"; sleep ${3:-1}; done; }; export -f sleeper
  9314.  
  9315.  
  9316.  
  9317. ##################################################
  9318. # Slow down CPU and IO for process and its   #
  9319. # offsprings                     #
  9320. ##################################################
  9321.  
  9322. ###### requires gawk: sudo apt-get install gawk
  9323. function slow2() { ionice -c3 renice -n 20 $(pstree `pidof $1` -p -a -u -A|gawk 'BEGIN{FS=","}{print $2}'|cut -f1 -d " ") ; }
  9324.  
  9325.  
  9326.  
  9327. ##################################################
  9328. # Get function's source              #
  9329. ##################################################
  9330.  
  9331. function source_print() { set | sed -n "/^$1/,/^}$/p"; }
  9332.  
  9333.  
  9334.  
  9335. ##################################################
  9336. # Spellchecking                  #
  9337. ##################################################
  9338.  
  9339. ###### I-Spell @ work: ENGLISH
  9340. # requires ispell: sudo apt-get install ispell
  9341. function spell()
  9342. {
  9343.     local CHATTO
  9344.     if [ $# -ne 1 ]; then
  9345.         echo -e "\033[1;32mUSAGE: \033[33mis word_to_check\033[0m"
  9346.     else
  9347.         CHATTO=$( echo $* | awk '{print $1}' )
  9348.         shift
  9349.         echo -e "----------------------------------------------------->\n"
  9350.         echo $CHATTO | ispell -a -m -B |grep -v "@"
  9351.         echo -e "----------------------------------------------------->"
  9352.     fi
  9353. }
  9354.  
  9355.  
  9356.  
  9357. ###### Google spell checker
  9358. function spellcheck() { typeset y=$@;curl -sd "<spellrequest><text>$y</text></spellrequest>" https://www.google.com/tbproxy/spell|sed -n '/s="[0-9]"/{s/<[^>]*>/ /g;s/\t/ /g;s/ *\(.*\)/Suggestions: \1\n/g;p}'|tee >(grep -Eq '.*'||echo -e "OK");}
  9359.  
  9360.  
  9361.  
  9362. ###### spell checks either a Web page URL or a file
  9363. # requires ispell: sudo apt-get install ispell
  9364. function webspell()
  9365. {
  9366. okaywords="$HOME/.okaywords"
  9367. tempout="/tmp/webspell.$$"
  9368. trap "/bin/rm -f $tempout" 0
  9369. if [ $# -eq 0 ] ; then
  9370.   echo "Usage: webspell file|URL" >&2;
  9371. fi
  9372. for filename
  9373. do
  9374.   if [ ! -f "$filename" -a "$(echo $filename|cut -c1-7)" != "http://" ] ; then
  9375.      continue;      # picked up directory in '*' listing
  9376.   fi
  9377.   lynx -dump $filename | tr ' ' '\n' | sort -u | \
  9378.     grep -vE "(^[^a-z]|')" | \
  9379.     # adjust the following line to produce just a list of misspelled words
  9380.     ispell -a | awk '/^\&/ { print $2 }' | \
  9381.     sort -u > $tempout
  9382.   if [ -r $okaywords ] ; then
  9383.     # if you have an okaywords file, screen okay words out
  9384.     grep -vif $okaywords < $tempout > ${tempout}.2
  9385.     mv ${tempout}.2 $tempout
  9386.   fi
  9387.   if [ -s $tempout ] ; then
  9388.     echo "Probable spelling errors: ${filename}"
  9389.     echo '-------' ; cat $tempout ; echo '========='
  9390.     cat $tempout | paste - - - -  | sed 's/^/  /'
  9391.   fi
  9392. done
  9393. }
  9394.  
  9395.  
  9396.  
  9397. ##################################################
  9398. # Cut a part of a video              #
  9399. ##################################################
  9400.  
  9401. # ("$1" for original file, "$2" for new file, "$3" is start time, & "$4" is length of video desired)
  9402. function splitvideo()
  9403. {
  9404. ffmpeg -vcodec copy -acodec copy -i "$1" -ss "$3" -t "$4" "$2"
  9405. }
  9406.  
  9407.  
  9408.  
  9409. ##################################################
  9410. # Posts a file to sprunge.us and copies the      #
  9411. # related url to the clipboard           #
  9412. ##################################################
  9413.  
  9414. function sprunge() { curl -s -F "sprunge=@$1" http://sprunge.us | xclip -selection clipboard && xclip -selection clipboard -o; }
  9415.  
  9416.  
  9417.  
  9418. ##################################################
  9419. # Stock prices - can be called two ways:     #
  9420. # stock novl  (this shows stock pricing):    #
  9421. # stock "novell"  (this way shows stock symbol   #
  9422. # for novell)                    #
  9423. ##################################################
  9424.  
  9425. function stock()
  9426. {
  9427. stockname=`lynx -dump http://finance.yahoo.com/q?s=${1} | grep -i ":${1})" | sed -e 's/Delayed.*$//'`
  9428. stockadvise="${stockname} - delayed quote."
  9429. declare -a STOCKINFO
  9430. STOCKINFO=(` lynx -dump http://finance.yahoo.com/q?s=${1} | egrep -i "Last Trade:|Change:|52wk Range:"`)
  9431. stockdata=`echo ${STOCKINFO[@]}`
  9432.    if [[ ${#stockname} != 0 ]] ;then
  9433.       echo "${stockadvise}"
  9434.       echo "${stockdata}"
  9435.          else
  9436.          stockname2=${1}
  9437.          lookupsymbol=`lynx -dump -nolist http://finance.yahoo.com/lookup?s="${1}" | grep -A 1 -m 1 "Portfolio" | grep -v "Portfolio" | sed 's/\(.*\)Add/\1 /'`
  9438.             if [[ ${#lookupsymbol} != 0 ]] ;then
  9439.             echo "${lookupsymbol}"
  9440.                else
  9441.                echo "Sorry $USER, I can not find ${1}."
  9442.             fi
  9443.    fi
  9444. }
  9445.  
  9446.  
  9447.  
  9448. ###### command line way to get the stock quote via Yahoo
  9449. function stock_()
  9450. {
  9451. curl -s 'http://download.finance.yahoo.com/d/quotes.csv?s=csco&f=l1'
  9452. }
  9453.  
  9454.  
  9455.  
  9456. ##################################################
  9457. # Stopwatch and Countdown Timer          #
  9458. ##################################################
  9459.  
  9460. function stopwatch() {
  9461. # copyright 2007 - 2010 Christopher Bratusek
  9462. BEGIN=$(date +%s)
  9463. while true; do
  9464.     NOW=$(date +%s)
  9465.     DIFF=$(($NOW - $BEGIN))
  9466.     MINS=$(($DIFF / 60))
  9467.     SECS=$(($DIFF % 60))
  9468.     echo -ne "Time elapsed: $MINS:`printf %02d $SECS`\r"
  9469.     sleep .1
  9470. done
  9471. }
  9472.  
  9473.  
  9474.  
  9475. ###### stopwatch with log
  9476. function stop_watch()
  9477. {
  9478. START=$( date +%s ); while true; do CURRENT=$( date +%s ) ; echo $(( CURRENT-START )) ; sleep 1 ; echo -n ^[[A ; done
  9479. }
  9480.  
  9481.  
  9482.  
  9483. ###### countdown clock
  9484. function countdown() { case "$1" in -s) shift;; *) set $(($1 * 60));; esac; local S=" "; for i in $(seq "$1" -1 1); do echo -ne "$S\r $i\r"; sleep 1; done; echo -e "$S\rBOOM!"; }
  9485.  
  9486.  
  9487.  
  9488. ###### countdown clock
  9489. alias countdown2='MIN=1 && for i in $(seq $(($MIN*60)) -1 1); do echo -n "$i, "; sleep 1; done; echo -e "\n\nBOOOM! Time to start."'
  9490.  
  9491.  
  9492.  
  9493. ##################################################
  9494. # Transcodes and streams a video over http on    #
  9495. # port 6789 (vlc required)           #
  9496. ##################################################
  9497.  
  9498. # function stream() { cvlc $1 --extraintf rc --sout
  9499. # 'transcode{vcodec=h264,vb=256,fps=12,scale=1,deinterlace,acodec=mp3,threads=3,ab=64,channels=2}:duplicate{dst=std{access=http,mux=ts,dst=0.0.0.0:6789}}';
  9500. # }
  9501.  
  9502.  
  9503.  
  9504. ##################################################
  9505. # Print the corresponding error message      #
  9506. ##################################################
  9507.  
  9508. function strerror() { python -c "import os; print os.strerror($1)"; }
  9509.  
  9510.  
  9511.  
  9512. ##################################################
  9513. # Function to split a string into an array   #
  9514. ##################################################
  9515.  
  9516. function string2array()
  9517. {
  9518. read -a ARR <<<'world domination now!'; echo ${ARR[2]};
  9519. }
  9520.  
  9521.  
  9522.  
  9523. ##################################################
  9524. # Check tcp-wrapping support             #
  9525. ##################################################
  9526.  
  9527. ###### returns TRUE if the application supports tcp-wrapping or FALSE if not by reading the shared libraries used by this application.
  9528. function supportsWrap() { ldd `which ${1}` | grep "libwrap" &>/dev/null && return 0 || return 1; }
  9529.  
  9530.  
  9531.  
  9532. ##################################################
  9533. # Swap 2 filenames around            #
  9534. ##################################################
  9535.  
  9536. ###### from Uzi's bashrc
  9537. function swap()
  9538. {
  9539.     local TMPFILE=tmp.$$
  9540.     [ $# -ne 2 ] && echo "swap: 2 arguments needed" && return 1
  9541.     [ ! -e $1 ] && echo "swap: $1 does not exist" && return 1
  9542.     [ ! -e $2 ] && echo "swap: $2 does not exist" && return 1
  9543.     mv "$1" $TMPFILE
  9544.     mv "$2" "$1"
  9545.     mv $TMPFILE "$2"
  9546. }
  9547.  
  9548.  
  9549.  
  9550. function swap2() { if [ -f "$1" -a -f "$2" ]; then mv "$1" "$1.$$" && mv "$2" "$1" && mv "$1.$$" "$2" && echo "Success"; else echo "Fail"; fi; }
  9551.  
  9552.  
  9553.  
  9554. ##################################################
  9555. # Switch two files (comes in handy)      #
  9556. ##################################################
  9557.  
  9558. function switchfile() {
  9559. mv $1 ${1}.tmp && $2 $1 && mv ${1}.tmp $2
  9560. }
  9561.  
  9562.  
  9563.  
  9564. ##################################################
  9565. # Creates a dated tarball            #
  9566. ##################################################
  9567.  
  9568. function tarball()
  9569. {
  9570.     name=$1
  9571.     shift
  9572.     tar zcvf $name-`date +%Y%m%d`.tar.gz "$@"
  9573. }
  9574.  
  9575.  
  9576.  
  9577. ##################################################
  9578. # Monitor progress of data through a pipeline    #
  9579. ##################################################
  9580.  
  9581. function tarcp() {
  9582.     if (( $# >= 2 )); then
  9583.         echo "copy ${@[1, -2]} => ${@[-1]}"
  9584.         # http://www.ivarch.com/programs/pv.shtml
  9585.         if which pv ; then
  9586.             tar -c -f - ${@[1, -2]} | pv -t -b -r | tar -x -f - -C ${@[-1]}
  9587.         else
  9588.             tar -c -v -f - ${@[1, -2]} | tar -x -f - -C ${@[-1]}
  9589.         fi
  9590.     else
  9591.         "error, not enough parameters."
  9592.         return 1
  9593.     fi
  9594. }
  9595.  
  9596.  
  9597.  
  9598. ##################################################
  9599. # TODO: fix so -s can be sent to cp      #
  9600. ##################################################
  9601.  
  9602. function tcp() {
  9603.         if [ "$1" = "-s" -o "$1" = "--set-target" ]; then
  9604.                 COPY_TARGET="$(realpath $2)";
  9605.         elif [ "$1" = "-h" -o "$1" = "--help" ]; then
  9606.                 echo "usage: tcp [-s|--set-target <dir>] | <mv args> <files>";
  9607.         else
  9608.                 cp --target-directory "$COPY_TARGET" "$@";
  9609.         fi
  9610. }
  9611.  
  9612.  
  9613.  
  9614. ##################################################
  9615. # Keeping your $HOME directory organized     #
  9616. ##################################################
  9617.  
  9618. ## having one temp dir for dls etc can quickly become mess, so try this tip to organise by date
  9619. # export TD="$HOME/temp/`date +'%Y-%m-%d'`"
  9620. # function td() {
  9621. #    td=$TD
  9622. #    if [ ! -z "$1" ]; then
  9623. #        td="$HOME/temp/`date -d "$1 days" +'%Y-%m-%d'`";
  9624. #    fi
  9625. #    mkdir -p $td; cd $td
  9626. #    unset td
  9627. # }
  9628.  
  9629.  
  9630.  
  9631. ##################################################
  9632. # Make the following commands run in         #
  9633. # background automatically:          #
  9634. ##################################################
  9635.  
  9636. ###### wrapper around xemacs/gnuserv ...
  9637. function te()
  9638. {
  9639.     if [ "$(gnuclient -batch -eval t 2>&-)" == "t" ]; then
  9640.         gnuclient -q "$@";
  9641.     else
  9642.         ( xemacs "$@" &);
  9643.     fi
  9644. }
  9645.  
  9646.  
  9647.  
  9648. ##################################################
  9649. # Set terminal title                 #
  9650. ##################################################
  9651.  
  9652. function terminal_title {
  9653.     echo -en "\033]2;$@\007"
  9654. }
  9655.  
  9656.  
  9657.  
  9658. ##################################################
  9659. # Display theme info                 #
  9660. ##################################################
  9661.  
  9662. function themeinfo() {
  9663.   if [ `pgrep emerald` ]; then
  9664.     echo "  Emerald:    `cat $HOME/.emerald/theme/theme.ini | grep description | awk -F= '{print $2}'`"
  9665.   else
  9666.     echo "  Metacity:   `gconftool-2 -g /apps/metacity/general/theme`"
  9667.   fi
  9668.   echo "  GTK:        `gconftool-2 -g /desktop/gnome/interface/gtk_theme`"
  9669.   echo "  Icons:      `gconftool-2 -g /desktop/gnome/interface/icon_theme`"
  9670.   echo "  Cursor:     `gconftool-2 -g /desktop/gnome/peripherals/mouse/cursor_theme`"
  9671.   echo "  Font:       `gconftool-2 -g /desktop/gnome/interface/font_name`"
  9672.   echo "  Wallpaper:  `gconftool-2 -g /desktop/gnome/background/picture_filename | xargs basename | cut -d. -f 1`"
  9673.   echo
  9674. }
  9675.  
  9676.  
  9677.  
  9678. ##################################################
  9679. # Thesaurus                  #
  9680. ##################################################
  9681.  
  9682. ###### requires dict: sudo apt-get install dict
  9683. function ths() {
  9684.     dict -d moby-thes $@
  9685. }
  9686.  
  9687.  
  9688.  
  9689. ##################################################
  9690. # Timer function                 #
  9691. ##################################################
  9692.  
  9693. ###### Elapsed time.  Usage:
  9694. #   t=$(timer)
  9695. #   ... # do something
  9696. #   printf 'Elapsed time: %s\n' $(timer $t)
  9697. #      ===> Elapsed time: 0:01:12
  9698. # If called with no arguments a new timer is returned.
  9699. # If called with arguments the first is used as a timer
  9700. # value and the elapsed time is returned in the form HH:MM:SS.
  9701. function timer()
  9702. {
  9703.     if [[ $# -eq 0 ]]; then
  9704.         echo $(date '+%s')
  9705.     else
  9706.         local  stime=$1
  9707.         etime=$(date '+%s')
  9708.         if [[ -z "$stime" ]]; then stime=$etime; fi
  9709.         dt=$((etime - stime))
  9710.         ds=$((dt % 60))
  9711.         dm=$(((dt / 60) % 60))
  9712.         dh=$((dt / 3600))
  9713.         printf '%d:%02d:%02d' $dh $dm $ds
  9714.     fi
  9715. }
  9716.  
  9717.  
  9718.  
  9719. ##################################################
  9720. # To examine lots of files and potentially move  #
  9721. # them to a common directory             #
  9722. ##################################################
  9723.  
  9724. ###### ex:  tmv -s /mnt/disk/5k
  9725. # ex:   make a playlist
  9726. # ex:   tmv eye-of-the-tiger.mp3 #  <-> mv eye-of-the-tiger.mp3 /mnt/disk/5k
  9727. function tmv() {
  9728.         if [ "$1" = "-s" -o "$1" = "--set-target" ]; then
  9729.                 MOVE_TARGET="$(realpath $2)";
  9730.         elif [ "$1" = "-h" -o "$1" = "--help" ]; then
  9731.                 echo "usage: tmv [-s|--set-target <dir>] | <mv args> <files>";
  9732.         else
  9733.                 mv --target-directory "$MOVE_TARGET" "$@";
  9734.         fi
  9735. }
  9736.  
  9737.  
  9738.  
  9739. ##################################################
  9740. # Top-ten commands               #
  9741. ##################################################
  9742.  
  9743. function top10() {
  9744.     # copyright 2007 - 2010 Christopher Bratusek
  9745.     history | awk '{a[$2]++ } END{for(i in a){print a[i] " " i}}' | sort -rn | head
  9746. }
  9747.  
  9748.  
  9749.  
  9750. ##################################################
  9751. # Switch tor on and off (requires privoxy)   #
  9752. ##################################################
  9753.  
  9754. function torswitch() {
  9755.     # copyright 2007 - 2010 Christopher Bratusek
  9756.     if [[ $EUID == 0 ]]; then
  9757.         case $1 in
  9758.             *on )
  9759.                 if [[ $(grep forward-socks4a /etc/privoxy/config) == "" ]]; then
  9760.                     echo "forward-socks4a / 127.0.0.1:9050 ." >> /etc/privoxy/config
  9761.                 else
  9762.                     sed -e 's/\# forward-socks4a/forward-socks4a/g' -i /etc/privoxy/config
  9763.                     /etc/init.d/tor restart
  9764.                     /etc/init.d/privoxy restart
  9765.                 fi
  9766.             ;;
  9767.             *off )
  9768.                 sed -e 's/forward-socks4a/\# forward-socks4a/g' -i /etc/privoxy/config
  9769.                 /etc/init.d/tor restart
  9770.                 /etc/init.d/privoxy restart
  9771.             ;;
  9772.         esac
  9773.     fi
  9774. }
  9775.  
  9776.  
  9777.  
  9778. ##################################################
  9779. # Moves specified files to ~/.Trash      #
  9780. ##################################################
  9781.  
  9782. ###### will not overwrite files that have the same name
  9783. function trashit()
  9784. {   local trash_dir=$HOME/.Trash
  9785.     for file in "$@" ; do
  9786.         if [[ -d $file ]] ; then
  9787.             local already_trashed=$trash_dir/`basename $file`
  9788.             if [[ -n `/bin/ls -d $already_trashed*` ]] ; then
  9789.                 local count=`/bin/ls -d $already_trashed* | /usr/bin/wc -l`
  9790.                 count=$((++count))
  9791.                 /bin/mv --verbose "$file" "$trash_dir/$file$count"
  9792.                 continue
  9793.             fi
  9794.         fi
  9795.         /bin/mv --verbose --backup=numbered "$file" $HOME/.Trash
  9796.     done
  9797. }
  9798.  
  9799.  
  9800.  
  9801. ##################################################
  9802. # Tree stuff                     #
  9803. ##################################################
  9804.  
  9805. ###### shows directory tree (requires 'tree': sudo apt-get install tree)
  9806. function treecd() {
  9807.     builtin cd "${@}" &>/dev/null
  9808.     . $BSNG_RC_DIR/dirinfo/display
  9809.     dirinfo_display
  9810.     echo -e "${epink}content:"
  9811.     tree -L 1 $TREE_OPTS
  9812.     echo "$PWD" > $HOME/.lastpwd
  9813. }
  9814.  
  9815.  
  9816.  
  9817. ###### displays a tree of the arborescence
  9818. function treefind() {
  9819.     find "$@" | sed 's/[^/]*\//|   /g;s/| *\([^| ]\)/+--- \1/'
  9820. }
  9821.  
  9822.  
  9823.  
  9824. ##################################################
  9825. # Search for a show at TV.COM            #
  9826. ##################################################
  9827.  
  9828. function tvcom() {
  9829. firefox "http://www.tv.com/search.php?type=11&stype=all&tag=search%3Bfrontdoor&qs="${@}"&stype=program" &
  9830. }
  9831.  
  9832.  
  9833.  
  9834. ##################################################
  9835. # Update twitter via curl as Function        #
  9836. ##################################################
  9837.  
  9838. function tweet() { curl -u "$1" -d status="$2" "http://twitter.com/statuses/update.xml"; }
  9839.  
  9840.  
  9841.  
  9842. ##################################################
  9843. # Changes spaces to underscores in names     #
  9844. ##################################################
  9845.  
  9846. function underscore()
  9847. {
  9848.     for f in * ; do
  9849.         [ "${f}" != "${f// /_}" ]
  9850.         mv -- "${f}" "${f// /_}"
  9851.     done
  9852. }
  9853.  
  9854.  
  9855.  
  9856. ##################################################
  9857. # Remove all files created by latex      #
  9858. ##################################################
  9859.  
  9860. function unlatex() {
  9861. if [ "$1" == "" ]; then
  9862. return
  9863. fi
  9864. i=${1%%.*}
  9865. rm -f $i.aux $i.toc $i.lof $i.lot $i.los $i.?*~ $i.loa $i.log $i.bbl $i.blg $i.glo
  9866. rm -f $i.odt $i.tns $i.fax $i.bm $i.out $i.nav $i.snm
  9867. rm -f $i.mtc* $i.bmt
  9868. mv -f $i.dvi .$i.dvi
  9869. mv -f $i.ps .$i.ps
  9870. mv -f $i.pdf .$i.pdf
  9871. rm -f $i.dvi $i.ps $i.pdf
  9872. unset i
  9873. }
  9874.  
  9875.  
  9876.  
  9877. ##################################################
  9878. # Up to top directory                #
  9879. ##################################################
  9880.  
  9881. function up() {
  9882. # copyright 2007 - 2010 Christopher Bratusek
  9883. [ "${1/[^0-9]/}" == "$1" ] && {
  9884.         local ups=""
  9885.         for ((i=1; i<=$1; i++))
  9886.         do
  9887.                 ups=$ups"../"
  9888.         done
  9889.         cd $ups
  9890.         }
  9891. }
  9892.  
  9893.  
  9894.  
  9895. ##################################################
  9896. # Easily decode unix-time (function)         #
  9897. ##################################################
  9898.  
  9899. function utime() { perl -e "print localtime($1).\"\n\"";}
  9900.  
  9901.  
  9902.  
  9903. ##################################################
  9904. # Checks to ensure that all              #
  9905. # environment variables are valid        #
  9906. ##################################################
  9907.  
  9908. ###### looks at SHELL, HOME, PATH, EDITOR, MAIL, and PAGER
  9909. function validator()
  9910. {
  9911. errors=0
  9912. function in_path()
  9913. {
  9914.   # given a command and the PATH, try to find the command. Returns
  9915.   # 1 if found, 0 if not.  Note that this temporarily modifies the
  9916.   # the IFS input field seperator, but restores it upon completion.
  9917.   cmd=$1    path=$2    retval=0
  9918.   oldIFS=$IFS; IFS=":"
  9919.   for directory in $path
  9920.   do
  9921.     if [ -x $directory/$cmd ] ; then
  9922.       retval=1      # if we're here, we found $cmd in $directory
  9923.     fi
  9924.   done
  9925.   IFS=$oldIFS
  9926.   return $retval
  9927. }
  9928. function validate()
  9929. {
  9930.   varname=$1    varvalue=$2
  9931.   if [ ! -z $varvalue ] ; then
  9932.     if [ "${varvalue%${varvalue#?}}" = "/" ] ; then
  9933.       if [ ! -x $varvalue ] ; then
  9934.         echo "** $varname set to $varvalue, but I cannot find executable."
  9935.         errors=$(( $errors + 1 ))
  9936.       fi
  9937.     else
  9938.       if in_path $varvalue $PATH ; then
  9939.         echo "** $varname set to $varvalue, but I cannot find it in PATH."
  9940.         errors=$(( $errors + 1 ))
  9941.       fi
  9942.     fi
  9943.   fi
  9944. }
  9945. ####### Beginning of actual shell script #######
  9946. if [ ! -x ${SHELL:?"Cannot proceed without SHELL being defined."} ] ; then
  9947.   echo "** SHELL set to $SHELL, but I cannot find that executable."
  9948.   errors=$(( $errors + 1 ))
  9949. fi
  9950. if [ ! -d ${HOME:?"You need to have your HOME set to your home directory"} ]
  9951. then
  9952.   echo "** HOME set to $HOME, but it's not a directory."
  9953.   errors=$(( $errors + 1 ))
  9954. fi
  9955. # Our first interesting test: are all the paths in PATH valid?
  9956. oldIFS=$IFS; IFS=":"     # IFS is the field separator. We'll change to ':'
  9957. for directory in $PATH
  9958. do
  9959.   if [ ! -d $directory ] ; then
  9960.       echo "** PATH contains invalid directory $directory"
  9961.       errors=$(( $errors + 1 ))
  9962.   fi
  9963. done
  9964. IFS=$oldIFS             # restore value for rest of script
  9965. # Following can be undefined, & also be a progname, rather than fully qualified path.
  9966. # Add additional variables as necessary for your site and user community.
  9967. validate "EDITOR" $EDITOR
  9968. validate "MAILER" $MAILER
  9969. validate "PAGER"  $PAGER
  9970. # and, finally, a different ending depending on whether errors > 0
  9971. if [ $errors -gt 0 ] ; then
  9972.   echo "Errors encountered. Please notify sysadmin for help."
  9973. else
  9974.   echo "Your environment checks out fine."
  9975. fi
  9976. }
  9977.  
  9978.  
  9979.  
  9980. ##################################################
  9981. # Run a command, redirecting output to a file,   #
  9982. # then edit the file with vim            #
  9983. ##################################################
  9984.  
  9985. function vimcmd() { $1 > $2 && vim $2; }
  9986.  
  9987.  
  9988.  
  9989. ##################################################
  9990. # Crawl a webpage for links          #
  9991. ##################################################
  9992.  
  9993. function webcrawl()
  9994. {
  9995. lynx -dump $1 | grep -A999 "^References$" | tail -n +3 | awk '{print $2 }'
  9996. }
  9997.  
  9998.  
  9999.  
  10000. ##################################################
  10001. # Telling you from where your commit come from   #
  10002. ##################################################
  10003.  
  10004. function where()
  10005. {
  10006. COUNT=0; while [ `where_arg $1~$COUNT | wc -w` == 0 ]; do let COUNT=COUNT+1; done; echo "$1 is ahead of "; where_arg $1~$COUNT; echo "by $COUNT commits";};function where_arg(){ git log $@ --decorate -1 | head -n1 | cut -d ' ' -f3- ;
  10007. }
  10008.  
  10009.  
  10010.  
  10011. ##################################################
  10012. # Check hosts that are online            #
  10013. ##################################################
  10014.  
  10015. ###### for those who DO NOT USE their /etc/hosts file for name resolution
  10016. # Function whoisonline adapted by:  dewar1
  10017. # This can look through resolv.conf file for address of nameservers
  10018. # (note: THIS WILL ONLY WORK IF YOU USE LOCAL NAMESERVERS! Nameservers
  10019. # from your ISP will render this function useless). It then cuts result to
  10020. # show just first 3 octets of IP address and runs nmap just as original function.
  10021. if which nmap 2>&1 > /dev/null; then
  10022.   function whodat()
  10023.   {
  10024.     if [ -n "$1" ]; then
  10025.       net="$1"
  10026.     else
  10027.       net=$(cat /etc/resolv.conf | grep 'nameserver' | cut -c12-26 | awk -F '.' '{print $1"."$2"."$3".0/24"}')
  10028.     fi
  10029.     echo "testing $net for online hosts"
  10030.     nmap -sP $net | awk '/Host/ && /up/ { print $0; }'
  10031.     echo "done"
  10032. }
  10033. fi
  10034.  
  10035.  
  10036.  
  10037. ###### for those who USE their /etc/hosts file for name resolution
  10038. #if which nmap 2>&1 > /dev/null; then
  10039. #  function whoisonline()
  10040. #  {
  10041. #    if [ -n "$1" ]; then
  10042. #      net="$1"
  10043. #    else
  10044. #      net=$(grep `hostname` /etc/hosts | awk -F '.' '{ print $1"."$2"."$3".0/24"}')
  10045. #    fi
  10046. #    sh_info "testing $net for online boxes"
  10047. #    sudo nmap -sP $net | awk '/Host/ && /up/ { print $0; }'
  10048. #    sh_success "done"
  10049. #  }
  10050. #fi
  10051.  
  10052.  
  10053.  
  10054. ##################################################
  10055. # Wipe command (uses 'shred', not 'wipe',    #
  10056. # which I think is better (sudo apt-get      #
  10057. # install wipe))                 #
  10058. ##################################################
  10059.  
  10060. function wipe_() {
  10061.     # copyright 2007 - 2010 Christopher Bratusek
  10062.     cryptsetup -d /dev/urandom -c aes-xts-plain create delete $1
  10063.     shred -vzn 0 /dev/mapper/delete
  10064.     sync && sleep 4
  10065.     cryptsetup remove delete
  10066. }
  10067.  
  10068.  
  10069.  
  10070. ##################################################
  10071. # ISO-writer                     #
  10072. ##################################################
  10073.  
  10074. function writeiso() {
  10075.     # copyright 2007 - 2010 Christopher Bratusek
  10076.     if [[ $CD_WRITER ]]; then
  10077.         cdrecord dev=$CD_WRITER "$1"
  10078.     else    cdrecord deV=/dev/dvdrw "$1"
  10079.     fi
  10080. }
  10081.  
  10082.  
  10083.  
  10084. ##################################################
  10085. # Xchown something               #
  10086. ##################################################
  10087.  
  10088. function xchown() {
  10089.     # copyright 2007 - 2010 Christopher Bratusek
  10090.     user="$1"
  10091.     shift
  10092.     for df in "$@";
  10093.         do su -c "chown -R $user:$user \"$df\"";
  10094.     done
  10095. }
  10096.  
  10097.  
  10098.  
  10099. ##################################################
  10100. # X delete - removes files with desired name     #
  10101. # in current directory               #
  10102. ##################################################
  10103.  
  10104. if [[ ${BASH_VERSINFO[0]} -ge "4" ]]; then
  10105. function xdel() {
  10106.         # copyright 2007 - 2010 Christopher Bratusek
  10107.         shopt -s globstar
  10108.         [[ "$@" != "" ]] &&
  10109.             { for argv in "$@"; do
  10110.                 rm -fv ./**/*"$argv"
  10111.             done }
  10112.     }
  10113. fi
  10114.  
  10115.  
  10116.  
  10117. ##################################################
  10118. # Adds some text in the terminal frame       #
  10119. ##################################################
  10120.  
  10121. function xtitle()
  10122. {
  10123.     case "$TERM" in
  10124.         *term | rxvt)
  10125.             echo -n -e "\033]0;$*\007" ;;
  10126.         *)
  10127.             ;;
  10128.     esac
  10129. }
  10130.  
  10131.  
  10132.  
  10133. ##################################################
  10134. # Busted... (Yaourt)                 #
  10135. ##################################################
  10136.  
  10137. function yaourt() {
  10138. EDITORBACKUP="$EDITOR";
  10139. export EDITOR=cat;
  10140. sudo yaourt "$@";
  10141. export EDITOR="$EDITORBACKUP";
  10142. export EDITORBACKUP=
  10143. }
  10144.  
  10145.  
  10146.  
  10147. ##################################################
  10148. # Overwrite a file with zeros            #
  10149. ##################################################
  10150.  
  10151. function zero() {
  10152.         case "$1" in
  10153.                 "")     echo "Usage: zero <file>"
  10154.  
  10155.                         return -1;
  10156.         esac
  10157.         filesize=`wc -c  "$1" | awk '{print $1}'`
  10158.         `dd if=/dev/zero of=$1 count=$filesize bs=1`
  10159. }
  10160.  
  10161.  
  10162.  
  10163. ##################################################
  10164. # To create a ZIP archive of a file or folder    #
  10165. ##################################################
  10166.  
  10167. function zipf() { zip -r "$1".zip "$1" ; }
  10168.  
  10169.  
  10170.  
  10171. ##################################################
  10172. ##################################################
  10173. ##################################################
  10174.  
  10175.  
  10176.  
  10177.  
  10178.  
  10179.  
  10180.  
  10181.  
  10182. ######################################################################################################################################################
  10183. ###### ALIASES ###### ALIASES ###### ALIASES ###### ALIASES ###### ALIASES ###### ALIASES ###### ALIASES ###### ALIASES ###### ALIASES ###### ALIASES ######
  10184. ######################################################################################################################################################
  10185.  
  10186.  
  10187.  
  10188.  
  10189.  
  10190.  
  10191.  
  10192.  
  10193. ##################################################
  10194. # App-specific                   #
  10195. ##################################################
  10196.  
  10197. alias audio='ncmpcpp'                               # music player
  10198. alias daemon-status='for a in deluged deluge rtorrent; do  (ps -u $USER|grep $a$ > /dev/null && echo $a running.) || echo $a not running.; done'    # list the status of the daemons :p
  10199. alias daggerfall='dosbox -conf ~/.dosbox.conf.daggerfall'           # launch dosbox with a preset configuration for Daggerfall
  10200. # alias deluge-link='echo http://'`hostname`':'$USER_WPRT'/'
  10201. alias ftp='ncftp Personal'
  10202. alias instaluj='sudo pacman-color -S'
  10203. alias links2g='links2 -g'
  10204. alias nano='nano -W -m'                             # disable annoying line wrapping
  10205. alias pacclean='sudo yaourt -Scc'                       # clean package cache
  10206. alias pacin='sudo yaourt -S'                            # install a specific package
  10207. alias pacman='yaourt'                               # switches from Pacman to Yaourt so we can troll the AUR
  10208. alias pacout='sudo yaourt -Rs'                          # Remove a specific package
  10209. alias pacsync='sudo yaourt -Sy'                         # Sync
  10210. alias pacup='sudo yaourt -Syu'                          # Sync & Update
  10211. alias rc='ssh ${MEDIAPCHOSTNAME} env DISPLAY=:0.0 rhythmbox-client --no-start'  # remote control for Rhythmbox on an Ubuntu Media PC
  10212. alias scrot='scrot -c -d 7'
  10213. alias spotify_next='$HOME/spotifycmd/spotify_cmd.exe next; $HOME/spotifycmd/spotify_cmd.exe status'
  10214. alias spotify_playpause='$HOME/spotifycmd/spotify_cmd.exe playpause'
  10215. alias spotify_prev='$HOME/spotifycmd/spotify_cmd.exe prev; $HOME/spotifycmd/spotify_cmd.exe status'
  10216. alias spotify_status='$HOME/spotifycmd/spotify_cmd.exe status'
  10217. alias spotify_stop='$HOME/spotifycmd/spotify_cmd.exe stop'
  10218. alias ss='gnome-screensaver-command -a'
  10219. alias start-deluged='start-stop-daemon -S --pidfile $HOME/.deluged.pid -u $USER -d $HOME -a /usr/bin/deluged -- --pidfile $HOME/.deluged.pid'
  10220. alias start-deluge-webui='start-stop-daemon -S --pidfile $HOME/.deluge-web.pid --background --make-pidfile -u $USER -d $HOME -a /usr/bin/deluge --  -u web'
  10221. alias start-rtorrent='(screen -ls|grep rtorrent > /dev/null || (screen -dmS rtorrent rtorrent && false)) && echo rtorrent is already running.'
  10222. alias start-vnc='vncserver :$USER_VPRT'
  10223. alias stop-deluged='start-stop-daemon -K --pidfile $HOME/.deluged.pid -u $USER -d $HOME -a /usr/bin/deluged -- --pidfile $HOME/.deluged.pid || killall -v -u $USER deluged'
  10224. alias stop-deluge-webui='start-stop-daemon -K --pidfile $HOME/.deluge-web.pid --make-pidfile -u $USER -d $HOME -a /usr/bin/deluge --  -u web;rm $HOME/.deluge-web.pid;'
  10225. alias stop-rtorrent='killall -u $USER rtorrent -q || echo rtorrent is not running'
  10226. alias stop-vnc='vncserver -kill :$USER_VPRT'
  10227. alias tetris='bastet'                               # bastardly tetris... awesome but deadly
  10228. alias tvtime-video0='tvtime-configure -d /dev/video0'
  10229. alias tvtime-video1='tvtime-configure -d /dev/video1'
  10230. alias tvtime-video2='tvtime-configure -d /dev/video2'
  10231. alias tvtime-video3='tvtime-configure -d /dev/video3'
  10232. alias tvtime-video4='tvtime-configure -d /dev/video4'
  10233. alias tvtime-video5='tvtime-configure -d /dev/video5'
  10234. alias wgeturlfromfile='wget -r -l1 -H -t1 -nd -N -np -A.jpg -erobots=off -i'    # -i file.txt
  10235. alias wget='wget -c'
  10236. alias yr='yaourt -Rs -C'
  10237. alias yss='yaourt -Ss -C'
  10238. alias ys='yaourt -S -C'
  10239. alias ysyu='yaourt -Syu -C'
  10240. alias ysy='yaourt -Sy -C'
  10241.  
  10242.  
  10243.  
  10244. ##################################################
  10245. # Apt-cache stuff                #
  10246. ##################################################
  10247.  
  10248. alias aptadd='sudo apt-cache add'
  10249. alias aptdepends='sudo apt-cache depends'
  10250. alias aptdotty='sudo apt-cache dotty'
  10251. alias aptdumpavail='sudo apt-cache dumpavail'
  10252. alias aptdump='sudo apt-cache dump'
  10253. alias aptgencaches='sudo apt-cache gencaches'
  10254. alias aptpkgnames='sudo apt-cache pkgnames'
  10255. alias aptpolicy='sudo apt-cache policy'
  10256. alias aptrdepends='sudo apt-cache rdepends'
  10257. alias aptsearch='sudo apt-cache search'
  10258. alias aptshowpkg='sudo apt-cache showpkg'
  10259. alias aptshowsrc='sudo apt-cache showsrc'
  10260. alias aptshow='sudo apt-cache show'
  10261. alias aptstats='sudo apt-cache stats'
  10262. alias aptunmet='sudo apt-cache unmet'
  10263. alias aptxvcg='sudo apt-cache xvcg'
  10264.  
  10265.  
  10266.  
  10267. ##################################################
  10268. # Apt-get stuff                  #
  10269. ##################################################
  10270.  
  10271. alias autoremove='sudo apt-get autoremove'
  10272. alias check='sudo apt-get check'
  10273. alias dist-upgrade='sudo apt-get dist-upgrade'
  10274. alias dselect-upgrade='sudo apt-get dselect-upgrade'
  10275. alias source='sudo apt-get source'
  10276.  
  10277.  
  10278.  
  10279. ##################################################
  10280. # Apt-history Stuff              #
  10281. ##################################################
  10282.  
  10283. alias historya='apt-history'
  10284. alias historyi='apt-history install'
  10285. alias historyre='apt-history remove'
  10286. alias historyro='apt-history rollback'
  10287. alias historyu='apt-history upgrade'
  10288.  
  10289.  
  10290.  
  10291. ##################################################
  10292. # Aptitude stuff                 #
  10293. ##################################################
  10294.  
  10295. alias autoclean='sudo aptitude autoclean'
  10296. alias build-dep='sudo aptitude build-dep'
  10297. alias changelog='sudo aptitude changelog'
  10298. alias clean='sudo aptitude clean'
  10299. alias download='sudo aptitude download'
  10300. alias forbid-version='sudo aptitude forbid-version'
  10301. alias forget-new='sudo aptitude forget-new'
  10302. alias full-upgrade='sudo aptitude full-upgrade'
  10303. alias hold='sudo aptitude hold'
  10304. alias install='sudo aptitude install'
  10305. alias linux-image='sudo aptitude search linux-image'        # linux-image kernel update check
  10306. alias markauto='sudo aptitude markauto'
  10307. alias purge='sudo aptitude purge'
  10308. alias reinstall='sudo aptitude reinstall'
  10309. alias remove='sudo aptitude remove'
  10310. alias search='sudo aptitude search'
  10311. alias show='sudo aptitude show'
  10312. alias unhold='sudo aptitude unhold'
  10313. alias unmarkauto='sudo aptitude unmarkauto'
  10314. alias update='sudo aptitude update'
  10315. alias upgrade='sudo aptitude safe-upgrade'
  10316. alias why-not='sudo aptitude why-not'
  10317. alias why='sudo aptitude why'
  10318.  
  10319.  
  10320.  
  10321. ##################################################
  10322. # Chown substitution                 #
  10323. ##################################################
  10324.  
  10325. alias chown-backgrounds='sudo chown -R $USER:$USER ~/Pictures/Backgrounds'
  10326. alias chown-backups='sudo chown -R $USER:$USER ~/Backups'
  10327. alias chown-books='sudo chown -R $USER:$USER ~/eBooks'
  10328. alias chown-desktop='sudo chown -R $USER:$USER ~/Desktop'
  10329. alias chown-documents='sudo chown -R $USER:$USER ~/Documents'
  10330. alias chown-downloads='sudo chown -R $USER:$USER ~/Downloads'
  10331. alias chown-drive-c='sudo chown -R $USER:$USER ~/.wine/drive_c'
  10332. alias chown-home='sudo chown -R $USER:$USER ~/'
  10333. alias chown-images='sudo chown -R $USER:$USER ~/Images'
  10334. alias chown-localhost='sudo chown -R $USER:$USER ~/var/www'
  10335. alias chown-music='sudo chown -R $USER:$USER ~/Music'
  10336. alias chown-nautilus-scripts='sudo chown -R $USER:$USER ~/.gnome2/nautilus-scripts'
  10337. alias chown-packages='sudo chown -R $USER:$USER ~/Packages'
  10338. alias chown-pictures='sudo chown -R $USER:$USER ~/Pictures'
  10339. alias chown-ppc='sudo chown -R $USER:$USER ~/PPC'
  10340. alias chown-public='sudo chown -R $USER:$USER ~/Public'
  10341. alias chown='sudo chown -R $USER:$USER'
  10342. alias chown-temp='sudo chown -R $USER:$USER ~/Temp'
  10343. alias chown-torrents='sudo chown -R $USER:$USER ~/Torrents'
  10344. alias chown-ubuntu-texts='sudo chown -R $USER:$USER ~/Documents/"Ubuntu Texts"'
  10345. alias chown-videos='sudo chown -R $USER:$USER ~/Videos'
  10346.  
  10347.  
  10348.  
  10349. ##################################################
  10350. # Command substitution               #
  10351. ##################################################
  10352.  
  10353. alias abs='sudo abs'
  10354. alias a='ssh-agent;ssh-add'
  10355. alias bt='aria2c --max-upload-limit=10K --seed-time=60 --listen-port=8900-8909'     # shortcut for downloading a torrent file on the command line
  10356. alias c='clear'
  10357. alias ci='vim'
  10358. alias ck='killall conky && conky -d'
  10359. alias cls='clear'
  10360. alias contents='/bin/tar -tzf'                              # can View the contents of a Tar file
  10361. alias cp='cp -iv'
  10362. alias d_='ssh 192.168.1.4'
  10363. alias dr='dirs -v'
  10364. alias ds_='dig +noauthority +noadditional +noqr +nostats +noidentify +nocmd +noquestion +nocomments'        # short and sweet output from dig(1)
  10365. alias e='espeak'
  10366. alias egrep='egrep –color=auto'
  10367. alias enote='vi ~/todo;~/motd.pl'
  10368. alias fgrep='fgrep –color=auto'
  10369. alias ge='geany'
  10370. alias go='startx'
  10371. alias grep='grep --color=auto'                              # highlight matched pattern
  10372. alias g_='mocp -G'
  10373. alias halt='sudo /sbin/halt'
  10374. alias h='history | grep $1'
  10375. alias hib='sudo pm-hibernate'
  10376. alias ie='wine iexplore.exe'                                # browse the Internet using Internet Explorer
  10377. alias im='centerim'                                     # terminal based instant messaging client
  10378. alias img='imgurbash'                                   # uploads image to imgur
  10379. alias irc='irssi'                                   # terminal based IRC
  10380. # alias irssi='screen -wipe; screen -A -U -x -R -S irssi irssi'             # for creating screen session containing IRSSI, named irssi, while checking if existing session is created
  10381. alias j='jobs -l'
  10382. alias kfx='killall firefox-bin'
  10383. alias kgp='killall gnome-panel'
  10384. alias k='kill'
  10385. alias kk='sendmail -d0.4 -bv root |less'
  10386. alias kn='killall nautilus'
  10387. alias last='last -a'
  10388. alias lock='clear && vlock -c'                              # clear and lock console (non-X) terminal
  10389. alias logs='tail -f /var/log/messages /var/log/*log'
  10390. alias m='~/bin/motd.pl'
  10391. alias mc='metacafe-dl -t'
  10392. alias me='vi ~/.muttrc'
  10393. alias mkdir='mkdir -p -v'
  10394. alias mktd='tdir=`mktemp -d` && cd $tdir'                       # make a temp dir, then immediately cd into it
  10395. alias m=mutt
  10396. alias more='less'
  10397. alias mp='screen -d -m mousepad'
  10398. alias mv='mv -iv'
  10399. alias na='nano'
  10400. alias nmr='sudo /etc/rc.d/networkmanager restart'
  10401. alias n='nautilus & exit'
  10402. alias np='mpc --format "np: [[%artist%] - [%title%] -                   #[[%album%] ##[%track%]#]]|[%file%]" | head -n 1'
  10403. alias nq='nautilus -q'
  10404. alias oe='wine msimn.exe'                               # read email with Outlook Express
  10405. alias packup='/bin/tar -czvf'                               # compress a file in tar format
  10406. alias parts='cat /proc/partitions'
  10407. # alias paste='ix'                                      # pastes to ix.ox pastebin service
  10408. alias paste='pastebinit'
  10409. alias path='echo -e ${PATH//:/\\n}'
  10410. alias pe='vi ~/.procmailrc'
  10411. alias pg='ps aux | grep'*                               # requires an argument
  10412. alias pi='`cat ~/.pi | grep ' ; alias addpi='echo "cd `pwd`" >> ~/.pi'          # fast access to any of your favorite directory.
  10413. alias ping='ping -c 10'
  10414. alias pjet='enscript -h -G -fCourier9 -d $LPDEST'                           # pretty-print using enscript
  10415. alias print='/usr/bin/lp -o nobanner -d $LPDEST'                            # assumes LPDEST is defined (default printer)
  10416. alias ps='ps auxf'
  10417. alias p_='for ((n=0;n<1;n++)); do dd if=/dev/urandom count=1 2> /dev/null | uuencode -m -| sed -ne 2p | cut -c-8; done' # creating password
  10418. alias :q='exit'
  10419. alias q='exit'
  10420. alias rcci='svn ci ~/rc/'
  10421. alias rcup='~/bin/rc_sync.sh'
  10422. alias rd='cd "`pwd -P`"'                                # if in directory containing symlink in path, change to "real" path
  10423. alias reboot='sudo /sbin/reboot'
  10424. # alias reboot='sudo shutdown -r now'                               # easy shutdown management
  10425. alias refresh='nautilus -q && killall gnome-panel'
  10426. alias rgrep='find . \( ! -name .svn -o -prune \) -type f -print0 | xargs -0 grep'   # rgrep: recursive grep without .svn
  10427. alias rh='rehash'
  10428. alias rmdir='rmdir -v'
  10429. alias rm='rm -iv'
  10430. alias root='sudo bash -l'                               # generic shortcut for switching to root user depending on system
  10431. # alias root='sudo -i'                                  # generic shortcut for switching to root user depending on system
  10432. # alias root='su -'                                 # generic shortcut for switching to root user depending on system
  10433. alias scx='screen -x'
  10434. alias sdi='sudo dpkg -i'
  10435. alias se='vi ~/.screenrc'
  10436. alias sg='sudo geany'
  10437. alias shutdown='sudo shutdown -h now'                           # proper restart
  10438. alias shutdownde='for ((;;)) do pgrep wget ||shutdown -h now; sleep 5; done'        # if download end, shutdown
  10439. alias sn='sudo nano'
  10440. alias split='split -d'
  10441. alias sql='mysql -p -u root'
  10442. alias sr='screen -d -RR'
  10443. # alias s='sudo'
  10444. # alias s_='screen -X screen'; s top; s vi; s man ls;                   # start a new command in a new screen window
  10445. alias sshdo='ssh -q -t root@localhost -- cd $PWD \&\& sudo'             # an alternative to sudo
  10446. alias sus='sudo pm-suspend'
  10447. alias svi='sudo vim'
  10448. alias tc='tar cfvz'
  10449. alias te='tail -50f /var/log/qmail/qmail-send/current | elog'
  10450. alias tf='tail -50f /var/log/iptables.log'
  10451. alias tm='tail -50f /var/log/messages.log'
  10452. alias ts='tail -50f /var/log/auth.log'
  10453. alias tweet='bti'
  10454. alias tx='tar xfvz'
  10455. alias u='mocp -P && sudo pm-suspend ; sleep 1s && mocp -U && setxkbmap -option terminate:ctrl_alt_bksp && xmodmap .config/caps-esc && ~/.fehbg' # something is messed up somewhere, dirty fix
  10456. alias unpack='/bin/tar -xzvpf'                              # uncompress a a Tar file
  10457. alias updatefont='fc-cache -v -f'
  10458. alias url='tinyurl'
  10459. alias urlping="ping -q -c 1 www.google.com|awk -F/ 'END{print $5}'"         # do one ping to URL: good in MRTG gauge graph to monitor connectivity
  10460. alias v='zless -N'                                  # -N means display line numbers (turn off line numbers with -n)
  10461. alias ve='vi ~/.vimrc'
  10462. alias vi='vim'
  10463. alias web='w3m'                                     # terminal based web browser
  10464. alias which='type -all'
  10465. alias win='/media/win'
  10466. alias wtf='watch -n 1 w -hs'
  10467. alias xee='cat /var/log/Xorg.0.log |grep EE'
  10468. alias xevs="xev | grep 'keycode\|button'"                       # only show button events for xev
  10469. alias xp='xprop | grep "WM_WINDOW_ROLE\|WM_CLASS" && echo "WM_CLASS(STRING) = \"NAME\", \"CLASS\""'
  10470. alias x='startx'
  10471. alias xww='cat /var/log/Xorg.0.log |grep WW'
  10472. alias yt='youtube-dl -t '
  10473. alias z='zenity --info --text="You will not believe it, but your command has finished now! :-)" --display :0.0' # get a desktop notification from the terminal
  10474. alias zen='fortune /usr/share/fortune/zen'
  10475.  
  10476.  
  10477.  
  10478. ##################################################
  10479. # Command substitution (for typos)       #
  10480. ##################################################
  10481.  
  10482. alias findgrep='grepfind'
  10483. alias mann='man'
  10484. alias moer='more'
  10485. alias moew='more'
  10486. alias updtae='update'
  10487. alias vf='cd'
  10488. alias xs='cd'
  10489. alias yauort='yaourt'
  10490. alias yoaurt='yaourt'
  10491. alias youart='yaourt'
  10492. alias yuaort='yaourt'
  10493. alias yuoart='yaourt'
  10494.  
  10495.  
  10496.  
  10497. ##################################################
  10498. # Computer cleanup               #
  10499. ##################################################
  10500.  
  10501. alias cleanup='sudo apt-get -y autoclean && sudo apt-get -y autoremove && sudo apt-get -y clean && sudo apt-get -y remove && sudo deborphan | xargs sudo apt-get -y remove --purge'
  10502. alias configpurge="sudo aptitude purge `dpkg --get-selections | grep deinstall | awk '{print $1}'`" # purge configuration files of removed packages on debian systems
  10503. alias kernelcleanup="dpkg -l 'linux-*' | sed '/^ii/!d;/'"$(uname -r | sed "s/\(.*\)-\([^0-9]\+\)/\1/")"'/d;s/^[^ ]* [^ ]* \([^ ]*\).*/\1/;/[0-9]/!d' | xargs sudo apt-get -y purge"                                     # remove all unused Linux Kernel headers, images & modules
  10504. alias orphaned='sudo deborphan | xargs sudo apt-get -y remove --purge'
  10505. alias tp='trash-put'                                            # sends files to trash instead of perm deleting w/rm
  10506. alias trash='rm -fr ~/.Trash'
  10507.  
  10508.  
  10509.  
  10510. ##################################################
  10511. # DD substitution                #
  10512. ##################################################
  10513.  
  10514. alias backup-sda='sudo dd if=/dev/hda of=/dev/sda bs=64k conv=notrunc,noerror'      # to backup the existing drive to a USB drive
  10515. alias cdcopy='sudo dd if=/dev/cdrom of=cd.iso'                      # for cdrom
  10516. alias cdiso='sudo dd if=/dev/hda of=cd.iso bs=2048 conv=sync,notrunc'           # to make an iso image of a CD
  10517. alias dd-sda-full='sudo dd if=/dev/urandom of=/dev/sda bs=8b conv=notrunc,noerror'  # to wipe hard drive with random data option (1)
  10518. alias dd-sda-r='sudo dd if=/dev/urandom of=/dev/sda bs=102400'              # to wipe hard drive with random data option (2)
  10519. alias dd-sda='sudo dd if=/dev/zero of=/dev/sda conv=notrunc'                # to wipe hard drive with zero
  10520. alias dd-sdb-full='sudo dd if=/dev/urandom of=/dev/sdb bs=8b conv=notrunc,noerror'  # to wipe hard drive with random data option (1)
  10521. alias dd-sdb-r='sudo dd if=/dev/urandom of=/dev/sdb bs=102400'              # to wipe hard drive with random data option (2)
  10522. alias dd-sdb='sudo dd if=/dev/zero of=/dev/sdb conv=notrunc'                # to wipe hard drive with zero
  10523. alias dd-sdc-full='sudo dd if=/dev/urandom of=/dev/sdc bs=8b conv=notrunc,noerror'  # to wipe hard drive with random data option (1)
  10524. alias dd-sdc-r='sudo dd if=/dev/urandom of=/dev/sdc bs=102400'              # to wipe hard drive with random data option (2)
  10525. alias dd-sdc='sudo dd if=/dev/zero of=/dev/sdc conv=notrunc'                # to wipe hard drive with zero
  10526. alias dd-sdd-full='sudo dd if=/dev/urandom of=/dev/sdd bs=8b conv=notrunc,noerror'  # to wipe hard drive with random data option (1)
  10527. alias dd-sdd-r='sudo dd if=/dev/urandom of=/dev/sdd bs=102400'              # to wipe hard drive with random data option (2)
  10528. alias dd-sdd='sudo dd if=/dev/zero of=/dev/sdd conv=notrunc'                # to wipe hard drive with zero
  10529. alias dd-sde-full='sudo dd if=/dev/urandom of=/dev/sde bs=8b conv=notrunc,noerror'  # to wipe hard drive with random data option (1)
  10530. alias dd-sde-r='sudo dd if=/dev/urandom of=/dev/sde bs=102400'              # to wipe hard drive with random data option (2)
  10531. alias dd-sde='sudo dd if=/dev/zero of=/dev/sde conv=notrunc'                # to wipe hard drive with zero
  10532. alias dd-sdf-full='sudo dd if=/dev/urandom of=/dev/sdf bs=8b conv=notrunc,noerror'  # to wipe hard drive with random data option (1)
  10533. alias dd-sdf-r='sudo dd if=/dev/urandom of=/dev/sdf bs=102400'              # to wipe hard drive with random data option (2)
  10534. alias dd-sdf='sudo dd if=/dev/zero of=/dev/sdf conv=notrunc'                # to wipe hard drive with zero
  10535. alias dd-sdg-full='sudo dd if=/dev/urandom of=/dev/sdg bs=8b conv=notrunc,noerror'  # to wipe hard drive with random data option (1)
  10536. alias dd-sdg-r='sudo dd if=/dev/urandom of=/dev/sdg bs=102400'              # to wipe hard drive with random data option (2)
  10537. alias dd-sdg='sudo dd if=/dev/zero of=/dev/sdg conv=notrunc'                # to wipe hard drive with zero
  10538. alias diskcopy='sudo dd if=/dev/dvd of=/dev/cdrecorder'
  10539. alias dvdcopy='sudo dd if=/dev/dvd of=dvd.iso'                      # for dvd
  10540. alias floppycopy='sudo dd if=/dev/fd0 of=floppy.image'                  # to duplicate a floppy disk to hard drive image file
  10541. alias partitioncopy='sudo dd if=/dev/sda1 of=/dev/sda2 bs=4096 conv=notrunc,noerror'    # to duplicate one hard disk partition to another hard disk partition
  10542. alias restore-sda='sudo dd if=/dev/sda of=/dev/hda bs=64k conv=notrunc,noerror'     # to restore from the USB drive to the existing drive
  10543. alias scsicopy='sudo dd if=/dev/scd0 of=cd.iso'                     # if cdrom is scsi
  10544.  
  10545.  
  10546.  
  10547. ##################################################
  10548. # Defragmenting and Fragmentation-Checking   #
  10549. # Tools                      #
  10550. ##################################################
  10551.  
  10552. alias defrag-home='defrag ~'            # uses 'defrag' function
  10553. alias defrag-root='defrag /root'        # uses 'defrag' function
  10554. alias defrag-system='defrag /'          # uses 'defrag' function
  10555. alias defrag2-home='defrag2 ~'          # uses 'defrag2' function
  10556. alias defrag2-root='defrag2 /root'      # uses 'defrag2' function
  10557. alias defrag2-system='defrag2 /'        # uses 'defrag2' function
  10558. alias fragcheck-home='fragcheck ~'      # uses 'fragcheck' function
  10559. alias fragcheck-root='fragcheck /root'      # uses 'fragcheck' function
  10560. alias fragcheck-system='fragcheck /'        # uses 'fragcheck' function
  10561. alias fragcheck2-home='fragcheck2 ~'        # uses 'fragcheck2' function
  10562. alias fragcheck2-root='fragcheck2 /root'    # uses 'fragcheck2' function
  10563. alias fragcheck2-system='fragcheck2 /'      # uses 'fragcheck2' function
  10564.  
  10565.  
  10566.  
  10567. ##################################################
  10568. # Directory shortcuts                #
  10569. ##################################################
  10570.  
  10571. alias back='cd $OLDPWD'
  10572. alias backgrounds='cd ~/Pictures/Backgrounds'
  10573. alias backups='cd ~/Backups'
  10574. alias books='cd ~/eBooks'
  10575. alias ..='cd ..'
  10576. alias ...='cd ../..'
  10577. alias ....='cd ../../..'
  10578. alias .....='cd ../../../..'
  10579. alias ......='cd ../../../../..'
  10580. alias documents='cd ~/Documents'
  10581. alias downloads='cd ~/Downloads'
  10582. alias drive-c='cd ~/.wine/drive_c'
  10583. alias dropbox='cd ~/Dropbox'
  10584. alias home='cd ~/'
  10585. alias images='cd ~/Images'
  10586. alias localhost='cd /var/www'
  10587. alias movies='cd ~/Videos'
  10588. alias music='cd ~/Music'
  10589. alias nautilus-scripts='cd ~/.gnome2/nautilus-scripts'
  10590. alias packages='cd ~/Packages'
  10591. alias packets='cd ~/.packets'
  10592. alias pictures='cd ~/Pictures'
  10593. alias ppc='cd ~/PPC'
  10594. alias public='cd ~/Public'
  10595. alias temp='cd ~/Temp'
  10596. alias test='cd ~/.test'
  10597. alias torrents='cd ~/Torrents'
  10598. alias ubuntu-texts='cd ~/Documents/"Ubuntu Texts"'
  10599. alias videos='cd ~/Videos'
  10600. alias webdesign='cd ~/Web/Design'
  10601. alias whereami='display_info'
  10602.  
  10603.  
  10604.  
  10605. ##################################################
  10606. # Espeak commands                #
  10607. ##################################################
  10608.  
  10609. alias espeak-file='espeak -s 150 -f'
  10610. alias espeak-us='espeak -v en-us -s 150'
  10611. alias espeak-wav='espeak -s 150 -w voice.wav'
  10612. alias espeak-wav-file='espeak -s 150 -w voice.wav -f'
  10613.  
  10614.  
  10615.  
  10616. ##################################################
  10617. # Git stuff                  #
  10618. ##################################################
  10619.  
  10620. alias gitouch='find . \( -type d -empty \) -and \( -not -regex ./\.git.* \) -exec touch {}/.gitignore \;'
  10621. alias gitup='git pull'
  10622. alias gitci='git commit -a -m'
  10623. alias gitco='git clone'
  10624. alias gita='git add'
  10625. alias gitb='git branch'
  10626. alias gitc='git checkout'
  10627.  
  10628.  
  10629.  
  10630. ##################################################
  10631. # Hardware Shortcuts                 #
  10632. ##################################################
  10633.  
  10634. alias 0='amixer set PCM 0'
  10635. alias -- -='amixer set PCM 2-'
  10636. alias +='amixer set PCM 2+'
  10637. alias blankcd='cdrecord -v dev=/dev/cdrom blank=fast gracetime=3'
  10638. alias blankdvd='cdrecord -v dev=/dev/dvd blank=fast gracetime=3'
  10639. alias blueoff='sudo /etc/rc.d/bluetooth stop'
  10640. alias blueon='sudo /etc/rc.d/bluetooth start'
  10641. alias blueres='sudo /etc/rc.d/bluetooth restart'
  10642. alias brand='growisofs -Z /dev/cdrw -v -l -R -J -joliet-long'
  10643. alias burnaudiocd='mkdir ./temp && for i in *.[Mm][Pp]3;do mpg123 -w "./temp/${i%%.*}.wav" "$i";done;cdrecord -pad ./temp/* && rm -r ./temp'    # burn a directory of mp3s to an audio cd
  10644. alias cdc='eject -t /dev/cdrecorder'
  10645. alias cdo='eject /dev/cdrecorder'
  10646. alias cruzer='mount /media/cruzer'
  10647. alias dvdc='eject -t /dev/dvd'
  10648. alias dvdo='eject /dev/dvd'
  10649. alias dvdrip='vobcopy -i /dev/dvd/ -o ~/DVDs/ -l'
  10650. alias dvdrip_='mplayer dvd://1 -dumpstream -alang es -dumpfile "$HOME/$DVD".mpg && ffmpeg -i "$HOME/$DVD".mpg -acodec libmp3lame -alang spa -vcodec libx264 -crf 26 -vpre hq -threads 0 "$HOME/$DVD.mp4"'
  10651. alias ipod='mount /media/ipod && cd /media/ipod'
  10652. alias kingston='mount /media/kingston && cd /media/kingston'
  10653. alias laptop_display='sudo cat /proc/acpi/video/VGA/LCD/brightness'     # set laptop display brightness (path may vary depending on laptop model
  10654. alias laptop_displays='echo <percentage> > /proc/acpi/video/VGA/LCD/brightness' # to discover the possible values for your display
  10655. alias mountcd='sudo mount -t is09660 /dev/sr0 /media/cdrom'
  10656. alias mountedinfo='df -hT'
  10657. alias mountiso='sudo mount ${1} ${2} -t iso9660 -o ro,loop=/dev/loop0'
  10658. alias mountwin='mount -t ntfs /dev/sda1 /media/win'
  10659. alias mp3='mount /media/mp3 && cd /media/mp3'
  10660. alias playm='for i in *.mp3; do play $i; done'
  10661. alias playo='for i in *.ogg; do play $i; done'
  10662. alias playw='for i in *.wav; do play $i; done'
  10663. alias scan='scanimage -L'
  10664. alias sd='mount /media/sd'
  10665. alias ucruzer='umount /media/cruzer'
  10666. alias uipod='umount /media/ipod'
  10667. alias ukingston='umount /media/kingston'
  10668. alias umountiso='sudo umount /media/iso'
  10669. alias ump3='umount /media/mp3'
  10670. alias usd='umount /media/sd'
  10671. alias uverbatim='umount /media/verbatim'
  10672. alias verbatim='mount /media/verbatim && cd /media/verbatim'
  10673.  
  10674.  
  10675.  
  10676. ##################################################
  10677. # Information                    #
  10678. ##################################################
  10679.  
  10680. alias biggest='BLOCKSIZE=1048576; du -x | sort -nr | head -10'              # show biggest directories
  10681. alias boothistory='for wtmp in `dir -t /var/log/wtmp*`; do last reboot -f $wtmp; done | less'
  10682. alias charcount='wc -c $1'                              # count number of characters in text file
  10683. alias cpu_hogs='ps wwaxr -o pid,stat,%cpu,time,command | head -10'          # to find CPU hogs
  10684. alias df='df -h -x tmpfs -x usbfs'                          # displays global disk usage by partition, excluding supermounted devices
  10685. alias directorydiskusage='du -s -k -c * | sort -rn'
  10686. alias dir='ls --color=auto --format=vertical'
  10687. alias diskwho='sudo iotop'
  10688. alias dmidecode='sudo dmidecode --type 17 | more'                   # check RAM sed and type in Linux
  10689. alias ducks='ls -A | grep -v -e '\''^\.\.$'\'' |xargs -i du -ks {} |sort -rn |head -16 | awk '\''{print $2}'\'' | xargs -i du -hs {}'   # useful alias to browse your filesystem for heavy usage quickly                        # to show processes reading/writing to disk
  10690. alias du='du -h --max-depth=1'                              # displays disk usage by directory, in human readable format
  10691. alias dush='du -sm *|sort -n|tail'                          # easily find megabyte eating files or directories
  10692. alias env2='for _a in {A..Z} {a..z};do _z=\${!${_a}*};for _i in `eval echo "${_z}"`;do echo -e "$_i: ${!_i}";done;done|cat -Tsv'    # print all environment variables, including hidden ones
  10693. alias exportkeys='sudo apt-key exportall > repokeys.txt'                # exports all repo keys info into single 'repokeys.txt' document
  10694. alias exportkey='sudo apt-key export'                           # show single repo key info using keyid found in 'sudo apt-key list'
  10695. alias ffind='sudo find / -name $1'
  10696. alias free='free -m'                                    # RAM and SWAP detail in MBs
  10697. alias freqwatch='watch --interval 1 "cat /proc/acpi/thermal_zone/THRM/*; cat /proc/cpuinfo | grep MHz; cat /proc/acpi/processor/*/throttling"'  # monitor cpu freq and temperature
  10698. alias hardware='sudo lshw -html > hardware.html'                    # overview of the hardware in the computer
  10699. # alias hgrep='history | grep --color=always'                       # search commands history
  10700. alias hiddenpnps='unhide (proc|sys|brute)'                      # forensic tool to find hidden processes and ports
  10701. alias hogc='ps -e -o %cpu,pid,ppid,user,cmd | sort -nr | head'              # display the processes that are using the most CPU time and memory
  10702. alias hogm='ps -e -o %mem,pid,ppid,user,cmd | sort -nr | head'              # display the processes that are using the most CPU time and memory
  10703. alias la_='ls -Al'                                  # show hidden files
  10704. alias l?='cat ~/technical/tips/ls'
  10705. alias lc='ls -ltcr'                                     # sort by and show change time, most recent last
  10706. alias ldir='ls -lhA |grep ^d'
  10707. alias ld='ls -ltr'                                  # sort by date
  10708. alias lfiles='ls -lhA |grep ^-'
  10709. alias lf="ls -Alh --color | awk '{k=0;for(i=0;i<=8;i++)k+=((substr(\$1,i+2,1)~/[rwx]/)*2^(8-i));if(k)printf(\" %0o \",k);print}'"   # full ls with octal+symbolic permissions
  10710. alias lgg='ls --color=always | grep --color=always -i'                  # quick case-insenstive partial filename search
  10711. alias lh='ls -Al'                                   # show hidden files
  10712. alias lh='ls -lAtrh'                                    # sort by date and human readable
  10713. alias libpath='echo -e ${LD_LIBRARY_PATH//:/\\n}'
  10714. alias li='ls -ai1|sort'                                 # sort by index number
  10715. alias linecount='wc -l $1'                              # count number of lines in text file
  10716. alias lk='ls -lSr'                                  # sort by size
  10717. alias llllll='ls -FlaXo --color=auto'                           # sort the extensions alphabetically; good for winfiles
  10718. alias lllll='ls -Fla --full-time -o -Q --color=auto'                    # whatever
  10719. alias llll='ls -laS --color=auto'                           # sort by size
  10720. alias lll='ls -Falot --color=auto'                          # sort by mod time
  10721. alias ll_='ls -l'                                   # long listing
  10722. alias l.='ls -d .[[:alnum:]]* 2> /dev/null || echo "No hidden file here..."'        # list only hidden files
  10723. alias l='ls -hF --color'                                # quick listing
  10724. alias lm_='ls -al |more'                                    # pipe through 'more'
  10725. alias ln='ln -s'
  10726. alias lr='ls -lR'                                   # recursice ls
  10727. alias lrt='ls -lart'                                    # list files with last modified at the end
  10728. alias lsam='ls -am'                                     # List files horizontally
  10729. alias lsdd='ls -latr'                                                   # sort by date
  10730. alias lsd='ls -l | grep "^d"'                               # list only directories
  10731. alias lsize='ls --sort=size -lhr'                           # list by size
  10732. alias lsl='ls -lah'                                                     # long list, human-readable
  10733. alias ls='ls -hF --color'                               # add colors for filetype recognition
  10734. alias lsnew='ls -Alh --color=auto --time-style=+%D | grep `date +%D`'
  10735. alias lss='ls -shaxSr'                                                  # sort by size
  10736. alias lsss='ls -lrt | grep $1'                              # to see something coming into ls output: lss
  10737. alias lsx='ls -ax'                                  # sort right to left rather then in columns
  10738. alias lt_='ls -alt|head -20'                                # 20, all, long listing, modification time
  10739. alias lt='ls -ltr'                                      # sort by date, most recent last
  10740. alias lu='ls -ltur'                                     # sort by and show access time, most recent last
  10741. alias lx='ls -lXB'                                  # sort by extension
  10742. # alias man='TERMINFO=~/.terminfo TERM=mostlike LESS=C PAGER=less man'          # cool colors for manpages
  10743. alias mem_hogs_ps='ps wwaxm -o pid,stat,vsize,rss,time,command | head -10'      # to find memory hogs
  10744. alias mem_hogs_top='top -l 1 -o rsize -n 10'                        # to find memory hogs
  10745. alias mem='~/.scripts/realmem'                              # estimates memory usage
  10746. alias mypc="hal-get-property --udi /org/freedesktop/Hal/devices/computer --key 'system.hardware.product'"       # show computer model
  10747. alias myps='/bin/ps -u "$USER" -o user,pid,ppid,pcpu,pmem,args|less'            # ps
  10748. alias numFiles='echo $(ls -1 | wc -l)'                          # numFiles: number of (non-hidden) files in current directory
  10749. alias packagelist="sudo aptitude search -F %p ~i --disable-columns"         # show list of all packages (columns)
  10750. alias packagelist_="sudo aptitude search -F %p ~i --disable-columns | sed 's/$/,/' | tr '\n\r' ' ' | sed 's/, $//'" # list all packages (1-liner)
  10751. alias phonesearch='grep '[0-9]\{3\}-[0-9]\{4\}' "$1"'                   # search phone #'s in file (requires XXX-XXX-XXXX format)
  10752. alias processbycpuusage="ps -e -o pcpu,cpu,nice,state,cputime,args --sort pcpu | sed '/^ 0.0 /d'"
  10753. alias processbymemusage='ps -e -o rss=,args= | sort -b -k1,1n | pr -TW$COLUMNS'
  10754. alias processtree='ps -e -o pid,args --forest'
  10755. alias pss='ps -ef | grep $1'                                # to check a process is running in a box with a heavy load: pss
  10756. alias sete='set|sed -n "/^`declare -F|sed -n "s/^declare -f \(.*\)/\1 ()/p;q"`/q;p"'    # display environment vars only, using set
  10757. alias showallaliases='compgen -A alias'                         # list bash alias defined in .bash_profile or .bashrc
  10758. alias showallfunctions='compgen -A function'                        # list bash functions defined in .bash_profile or .bashrc
  10759. alias showkeys='sudo apt-key list'                          # shows list of repository keys
  10760. alias sizeof='du -sh'
  10761. alias space='df -h'                                 # disk space usage
  10762. alias sshall='logwatch --service sshd --range all --detail high --print --archives'
  10763. alias sshtoday='logwatch --service sshd --range today --detail high --print --archives'
  10764. alias superfind='sudo find / ! \( -path /proc -prune -o -path /tmp -prune -o -path /dev -prune -o -path /mnt -prune \) -name'
  10765. alias top-commands='history | awk "{print $2}" | awk "BEGIN {FS="|"} {print $1}" |sort|uniq -c | sort -rn | head -10'   # show most popular commands
  10766. alias topforever='top -l 0 -s 10 -o cpu -n 15'                      # continual 'top' listing (every 10 sec) showing top 15 CPU things
  10767. alias topten='du -sk $(/bin/ls -A) | sort -rn | head -10'               # displays the top ten biggest folders/files in the current directory
  10768. alias top20='du -xk | sort -n | tail -20'                       # find the 20 biggest directories on the current filesystem
  10769. alias top_='xtitle Processes on $HOST && top'                       # uses the function 'xtitle'
  10770. alias treefind_="find . | sed 's/[^/]*\//|   /g;s/| *\([^| ]\)/+--- \1/'"       # displays a tree of the arborescence
  10771. alias tree='tree -Cs'                                   # nice alternative to 'ls'
  10772. alias unusedkernels="dpkg -l 'linux-*' | sed '/^ii/!d;/'"$(uname -r | sed "s/\(.*\)-\([^0-9]\+\)/\1/")"'/d;s/^[^ ]* [^ ]* \([^ ]*\).*/\1/;/[0-9]/!d'"                                           # show installed but unused linux headers, image, or modules
  10773. alias vdir='ls --color=auto --format=long'
  10774. alias ver='cat /etc/lsb-release'                            # Ubuntu version detail
  10775. alias version='sudo apt-show-versions'                          # show version
  10776. alias whichall='{ command alias; command declare -f; } | command which --read-functions --read-alias -a'        # which alias
  10777. alias wordcount='wc -w $1'                              # count number of words in text file
  10778.  
  10779.  
  10780.  
  10781. ##################################################
  10782. # Information (clock and date stuff)         #
  10783. ##################################################
  10784.  
  10785. alias bdate="date '+%a, %b %d %Y %T %Z'"
  10786. alias cal='cal -3'                                  # show 3 months by default
  10787. alias da='date "+%Y-%m-%d %A    %T %Z"'                         # date command
  10788. alias da_="date +'%a %Y-%m-%d %H:%M:%S %z'"                     # another date command
  10789. alias dateh='date --help|sed "/^ *%a/,/^ *%Z/!d;y/_/!/;s/^ *%\([:a-z]\+\) \+/\1_/gI;s/%/#/g;s/^\([a-y]\|[z:]\+\)_/%%\1_%\1_/I"|while read L;do date "+${L}"|sed y/!#/%%/;done|column -ts_'  # view all date formats, quick reference help alias
  10790. alias daysleft='echo "There are $(($(date +%j -d"Dec 31, $(date +%Y)")-$(date +%j))) left in year $(date +%Y)."'    # how many days until the end of the year
  10791. alias epochtime='date +%s'                              # report number of seconds since the Epoch
  10792. alias mytime='date +%H:%M:%S'                               # shows just the current time
  10793. alias ntpdate='sudo ntpdate ntp.ubuntu.com pool.ntp.org'                # time synchronisation with NTP
  10794. alias oclock='read -a A<<<".*.**..*....*** 8 9 5 10 6 0 2 11 7 4";for C in `date +"%H%M"|fold -w1`;do echo "${A:${A[C+1]}:4}";done'   # odd clock
  10795. alias onthisday='grep -h -d skip `date +%m/%d` /usr/share/calendar/*'           # on this day
  10796. alias secconvert='date -d@1234567890'                           # convert seconds to human-readable format
  10797. alias stamp='date "+%Y%m%d%a%H%M"'                          # timestamps
  10798. alias timestamp='date "+%Y%m%dT%H%M%S"'                         # date command that lets you create timestamps in ISO 8601 format
  10799. alias today='date +"%A, %B %-d, %Y"'
  10800. alias weeknum='date +%V'                                # perl one-liner to get the current week number
  10801.  
  10802.  
  10803.  
  10804. ##################################################
  10805. # Miscellaneous                  #
  10806. ##################################################
  10807.  
  10808. alias -- --='-;-'
  10809. alias -- ---='-;-;-'
  10810. alias -- ----='-;-;-;-'
  10811. alias -- -----='-;-;-;-;-'
  10812. alias ++='+;+'
  10813. alias +++='+;+;+'
  10814. alias ++++='+;+;+;+'
  10815. alias +++++='+;+;+;+;+'
  10816. alias addkey='sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys'
  10817. alias addrepo='sudo add-apt-repository'                         # add a repo to repo .list
  10818. alias alert_helper='history|tail -n1|sed -e "s/^\s*[0-9]\+\s*//" -e "s/;\s*alert$//"'   # notified when job run in terminal is done using NotifyOSD
  10819. alias alert='notify-send -i gnome-terminal "Finished Terminal Job" "[$?] $(alert_helper)"'  # usage: sleep 5; alert
  10820. alias alsamixer='alsamixer -V all'
  10821. alias bashrc-copy-r='sudo cp /root/.bashrc ~/.bashrc'
  10822. alias bashrc-copy='sudo cp ~/.bashrc /root/.bashrc'
  10823. alias bashrc-cpr='sudo cp ~/.bashrc /root/.bashrc && cp ~/.bashrc ~/Temp && gedit ~/.bashrc && exit'
  10824. alias bashrc='gedit ~/.bashrc & exit'
  10825. alias bashrc-root='sudo gedit ~/.bashrc & exit'
  10826. alias bashrc-temp='cp ~/.bashrc ~/Temp'
  10827. alias bbc='lynx -term=vt100 http://news.bbc.co.uk/text_only.stm'
  10828. alias bedit='vim ~/.bashrc; source ~/.bashrc'
  10829. alias beep='echo -en "\007"'                                # ring the bell
  10830. alias bgedit='gedit ~/.bashrc; source ~/.bashrc'
  10831. alias blipfm="mpg123 `curl -s http://blip.fm/all | sed -e 's#"#\n#g'  | grep mp3$  | xargs`"    # play random music from blip.fm
  10832. alias capture='IMAGE="$HOME/Pictures/capture-`date +%Y%m%d%H%M%S`.png"; import -frame $IMAGE; echo "Image saved as $IMAGE"' # save portion of desktop as image
  10833. alias cic='set completion-ignore-case On'                       # make tab-completion case-insensitive
  10834. alias clisp='clisp -q'
  10835. alias color1='sh ~/.scripts/termcolor1'                         # displays colorset 1
  10836. alias color2='sh ~/.scripts/termcolor2'                         # displays colerset 2
  10837. alias color3='sh ~/.scripts/termcolor3'                         # displays colorset 3
  10838. alias commentremove="sed 's/[[:blank:]]*#.*//; /^$/d' "$1""             # this will remove comments that are at the end of lines
  10839. alias counts=sort | uniq -c | sort -nr                          # a nice command for summarising repeated information
  10840. alias cut80='/usr/bin/cut -c 1-80'                          # truncate lines longer than 80 characters (for use in pipes)
  10841. alias debrepack='sudo dpkg-repack'                          # just an easier-to-remember alias for 'dpkg-repack'
  10842. alias differ='sdiff --suppress-common-lines'                        # bash alias for sdiff: differ
  10843. alias dmregister='lynx http://desmoinesregister.com'
  10844. alias du0='du --max-depth=0'
  10845. alias du1='du --max-depth=1'
  10846. alias ebrc='nano ~/.bashrc'
  10847. alias ebrcupdate='source ~/.bashrc'
  10848. alias edit='nano'
  10849. alias elog='tai64nlocal'
  10850. alias encryptall='for f in * ; do [ -f $f ] && openssl enc -aes-256-cbc -salt -in $f -out $f.enc -pass file:/tmp/password-file ; done'  # encrypt every file in current directory with 256-bit AES, retaining original
  10851. alias fixopera='rm -r ~/.opera/{mail,lock}'
  10852. alias fixres='xrandr --size 1600x1200'                              # reset resolution
  10853. alias fix_stty='stty sane'                              # restore terminal settings when they get completely screwed up
  10854. alias flv2ogg='for i in $(ls *.flv); do ffmpeg2theora -v 6 --optimize $i; done'     # convert all FLV's in a directory to Ogg Theora (video)
  10855. alias flvaudio='ffmpeg -i "$1" -f mp3 -vn -acodec copy ouput.mp3'           # extract sound from flv & make mp3
  10856. alias foldpb='pbpaste | fold -s | pbcopy'                       # make text in clipboard wrap so as to not exceed 80 characters
  10857. alias funkcje="grep -o '^[a-zA-Z]\{1,\}.(*)' ~/.bashrc"
  10858. alias gdbbt='gdb -q -n -ex bt -batch'                           # print stack trace of a core file without needing to enter gdb interactively
  10859. alias gifted='giftd -d && giFTcurs'
  10860. alias gitk='screen -d -m gitk'
  10861. alias gmail='sh /$HOME/.scripts/gmail.sh'
  10862. alias googlevideo='wget -qO- "VURL" | grep -o "googleplayer.swf?videoUrl\\\x3d\(.\+\)\\\x26thumbnailUrl\\\x3dhttp" | grep -o "http.\+" | sed -e's/%\([0-9A-F][0-9A-F]\)/\\\\\x\1/g' | xargs echo -e | sed 's/.\{22\}$//g' | xargs wget -O "$1"' # Google video download
  10863. alias gsop='gmplayer http://localhost:8909 -prefer-ipv4'
  10864. alias head='head -n $((${LINES:-`tput lines 2>/dev/null||echo -n 12`} - 2))'        # alias HEAD for automatic smart output
  10865. alias hiresvideo='mplayer -framedrop -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all'    # play high-res video files on a slow processor
  10866. alias image2pdf='convert -adjoin -page A4 *.jpeg multipage.pdf'             # convert images to a multi-page pdf
  10867. alias irb='irb --readline -r irb/completion -rubygems'
  10868. alias jargon='wget -m http://catb.org/~esr/jargon/html/ -nH --cut-dirs=2 -np -L -P ~/Jargon/'
  10869. alias kernbuild='make -j3 && make modules_install && ls -ld ../linux && date'       # compile kernel, install modules, display kernel vers & date
  10870. alias kfire='for i in `ps aux | grep [F]irefox `; do echo $i; kill $(($i)); done; '
  10871. # alias kfire='kill $(pidof firefox)'
  10872. # alias kfire='kill $(ps aux | awk '/firefox/ {print $2}' | tr '\n' ' ')'
  10873. alias killall='killall -u $USER -v'                             # only kill our own processes, and also be verbose about it
  10874. alias lastlog='lastlog | grep -v Never'
  10875. alias less='less -Mw'
  10876. alias lssd='ps ax | grep -v grep | grep -i firefox | while read pid; do kill "${pid%% *}"; done'
  10877. alias lstexfont='ls {/usr/share/texmf-dist/tex/latex/psnfss/*.sty,/usr/share/texmf-dist/tex/latex/pxfonts/*.sty}'
  10878. alias lvim="vim -c \"normal '0\""                           # open the last file you edited in Vim.
  10879. alias makepasswd='makepasswd -minchars 8'
  10880. alias make_='xtitle Making $(basename $PWD) ; make'                 # uses the function 'xtitle'
  10881. alias mencoder-join='mencoder -forceidx -ovc copy -oac copy -o'             # just add: whatever.avi whatever.pt1.avi whatever.pt2.avi ...
  10882. alias mic_record='arecord -q -f cd -r 44100 -c2 -t raw | lame -S -x -h -b 128 - `date +%Y%m%d%H%M`.mp3' # record microphone input and output to date stamped mp3 file
  10883. alias minicom='minicom -c on'                               # enable colour (sudo apt-get install minicom)
  10884. alias mkdsp='sudo mknod /dev/dsp c 14 3 && sudo chmod 777 /dev/dsp'         # remake /dev/dsp
  10885. alias mkpkg='makepkg -csi'
  10886. alias mp3ogg='mp32ogg *.mp3 && rm *.mp3'
  10887. alias mpfb='mplayer -vo fbdev2 -fs -zoom -xy 1440'
  10888. alias mplayer_yt='mplayer -fs $(echo "http://youtube.com/get_video.php?$(curl -s "$1" | sed -n "/watch_fullscreen/s;.*\(video_id.\+\)&title.*;\1;p")")'                                     # stream YouTube URL directly to mplayer
  10889. alias mtrue='sudo truecrypt /media/usbdisk/$USER.tc ~/$USER'
  10890. alias n2r='sudo /etc/init.d/nginx stop && sleep 2 && sudo /etc/init.d/nginx start'
  10891. alias ncftp='xtitle ncFTP ; ncftp'                          # uses the function 'xtitle'
  10892. alias nytimes='lynx -term=vt100 http://nytimes.com'
  10893. alias passwords='passwd && rm -rf ~/.gnome2/keyrings/*'                 # removes keyring passwords and lets you change user password
  10894. alias ppa-purge='sudo ppa-purge'
  10895. alias pstree='/sw/bin/pstree -g 2 -w'
  10896. alias puttyreload='export TERM=putty && source ~/.bashrc'
  10897. alias quota='quota -s'                                  # human readable quota!
  10898. alias recursivetouch='find . -exec touch {} \;'                     # be careful with this as it can modify time stamp of files
  10899. alias repo='gksudo gedit /etc/apt/sources.list'
  10900. alias restart-apache='sudo /etc/init.d/apache2 restart'
  10901. alias rkhunter='sudo rkhunter -c'
  10902. alias rmao='find . -iname a.out -exec rm {} \;'
  10903. alias rm_DS_Store_files='find . -name .DS_Store -exec rm {} \;'             # removes all .DS_Store file from the current dir and below
  10904. alias rsync-me='sudo rsync -a -v --progress --delete --modify-window=1 -s $HOME /home/rsync'
  10905. alias scpresume='rsync --partial --progress --rsh=ssh'
  10906. # alias screencast='ffmpeg -f alsa -ac 2 -i hw:0,0 -f x11grab -r 30 -s 1280x800+0+0 -i :0.0 -acodec pcm_s16le -vcodec libx264 -vpre lossless_ultrafast -threads 0 -y output.mkv'
  10907. # alias screencast='ffmpeg -f x11grab -r 30 -s 1280x800 -i :0.0 $HOME/outputFile.mpg'   # record a screencast and convert it to an mpeg
  10908. alias screencast="ffmpeg -y -f alsa -ac 2 -i pulse -f x11grab -r 30 -s `xdpyinfo | grep 'dimensions:'|awk '{print $2}'` -i :0.0 -acodec pcm_s16le output.wav -an -vcodec libx264 -vpre lossless_ultrafast -threads 0 output.mp4"        # capture video of a linux desktop
  10909. alias sdiff='/usr/bin/sdiff --expand-tabs --ignore-all-space --strip-trailing-cr --width=160'   # sdiff the way it was at IBM
  10910. alias sdirs='source ~/.dirs'
  10911. alias service='sudo service'                                # access a system service
  10912. alias sh_diff='diff -abBpur'
  10913. alias sh_indent='indent -nsaf -npcs -cli2 -i2 -lp -nprs -nsaw -nut -cbi2 -bli0 -bls -nbad -npsl'
  10914. alias shot!='archey && scrot -d 5 -c screen_`date +%Y-%m-%d`.png'           # is also a function of shot which does the screen for one window
  10915. alias show_='cat ~/.dirs'
  10916. alias show-colors='~/.bin/colors.sh'
  10917. alias show-info='~/.bin/info.pl'
  10918. alias show_options='shopt'                              # show_options: display bash options settings
  10919. alias showrepo='cat /etc/apt/sources.list `ls /etc/apt/sources.list.d/*.list` | egrep -v "^$"'
  10920. alias sh_svnstat="svn status | awk '/^[^?]/'"
  10921. alias sourcea='source ~/.aliases.bash'                          # to source this file (to make changes active after editing)
  10922. alias ssinfo='perl ~/.scripts/ssinfo.pl'
  10923. alias stopflash='for i in ~/.adobe ~/.macromedia ; do ( rm $i/ -rf ; ln -s /dev/null $i ) ; done'   # brute force way to block all LSO cookies with the non-free Flash browser plugin
  10924. # alias svnaddall='find "$PWD" -exec svn add {} 2>/dev/null \;'             # add all files recursively
  10925. alias svnaddall='svn status | grep "^\?" | awk "{print \$2}" | xargs svn add'
  10926. alias svndelall='svn status | grep "^\!" | awk "{print \$2}" | xargs svn delete'
  10927. alias svnrmallentries='find . -name .svn -print0 | xargs -0 rm -rf'         # remove all .svn directories recursively
  10928. alias tailm='multitail'
  10929. alias tarred='( ( D=`builtin pwd`; F=$(date +$HOME/`sed "s,[/ ],#,g" <<< ${D/${HOME}/}`#-%F.tgz); tar --ignore-failed-read --transform "s,^${D%/*},`date +${D%/*}.%F`,S" -czPf "$"F "$D" &>/dev/null ) & )'                 # create date-based tgz of current dir (runs in background)
  10930. # alias themeinfo='perl ~/Scripts/info.pl'
  10931. alias thumbit='mogrify -resize 25%'
  10932. alias tinyurl='~/.scripts/tinyurl'                          # converts url to tinyurl
  10933. alias tkeys='tmux list-keys'                                # shows all tmux keys
  10934. alias trace='~/.scripts/trace'                              # visual traceroute
  10935. alias txt2md='rename 's/\.txt$/\.md$/i' *'                      # batch rename extension of all .txt files to .md files in a folder
  10936. alias ugrub2='sudo update-grub2'                            # update grub2
  10937. alias ugrub='sudo update-grub'                              # update grub
  10938. alias updatedb='sudo updatedb'
  10939. alias updatefonts='sudo fc-cache -vf'
  10940. alias usbb='rsync -avz /media/usbdisk/ ~/backup/usb/'
  10941. alias utrue='sudo truecrypt -d'
  10942. alias webcam='mplayer -cache 128 -tv driver=v4l2:width=176:height=177 -vo xv tv:// -noborder -geometry "95%:93%" -ontop'    # mplayer webcam window for screencasts
  10943. alias webshare='python -c "import SimpleHTTPServer; SimpleHTTPServer.test();"'
  10944. alias wiki='wikipedia2text -p'                              # convert wiki to text output
  10945. alias xinitrc='vim ~/.xinitrc'
  10946. alias xsnow='(killall xsnow ; sleep 3 ; exec xsnow -nosanta -notrees -norudolf -nokeepsnow >& /dev/null &)' # xsnow
  10947.  
  10948.  
  10949.  
  10950. ##################################################
  10951. # Miscellaneous Fun              #
  10952. ##################################################
  10953.  
  10954. alias 99bottles='x="bottles of beer";y="on the wall";for b in {99..1};do echo "$b $x $y, $b $x. Take one down pass it around, $(($b-1)) $x $y"; sleep 3;done'
  10955. alias addictive='count="1" ; while true ; do read next ; if [[ "$next" = "$last" ]] ; then count=$(($count+1)) ; echo "$count" ; else count="1" ; echo $count ; fi ; last="$next" ; done'                               # simple addicting bash game
  10956. alias busy='for i in `seq 0 100`;do timeout 6 dialog --gauge "Install..." 6 40 "$i";done'   # pretend to be busy in office to enjoy a cup of coffee
  10957. alias busy2='my_file=$(find /usr/include -type f | sort -R | head -n 1); my_len=$(wc -l $my_file | awk "{print $1}"); let "r = $RANDOM % $my_len" 2>/dev/null; vim +$r $my_file'
  10958. alias busy3='cat /dev/urandom | hexdump -C | highlight ca fe 3d 42 e1 b3 ae f8 | perl -MTime::HiRes -pnE "Time::HiRes::usleep(rand()*1000000)"'
  10959. alias earth='rm -f ~/Pictures/Backgrounds/mercator.jpg && wget -r -N http://static.die.net/earth/mercator/1600.jpg -O ~/Pictures/Backgrounds/mercator.jpg && gconftool-2 --type string --set /desktop/gnome/background/picture_filename ~/Pictures/Backgrounds/mercator.jpg'    # live earth wallpaper
  10960. # alias earth='mv ~/Pictures/Backgrounds/mercator.jpg ~/Pictures/Backgrounds/mercator.`timestamp`.jpg | wget -r -N http://static.die.net/earth/mercator/1600.jpg -O ~/Pictures/Backgrounds/mercator.jpg && gconftool-2 --type string --set /desktop/gnome/background/picture_filename ~/Pictures/Backgrounds/mercator.jpg'  # live earth wallpaper (downloads and saves each time)
  10961. alias einsteiny='A=1;B=100;X=0;C=0;N=$[$RANDOM%$B+1];until [ $X -eq $N ];do read -p "N between $A and $B. Guess? " X;C=$(($C+1));A=$(($X<$N?$X:$A));B=$(($X>$N?$X:$B));done;echo "Took you $C tries, Einstein";'                        # numbers guessing game
  10962. alias etchasketch='c=12322123;x=20;y=20;while read -sn1 p;do k=${c:(p-1)*2:2};let x+=$((k/10-2));let y+=$((k%10-2));echo -en \\033[$y\;"$x"HX;done' # use the 1 2 3 and 4 keys to move the cursor around the screen (It's an etch-a-sketch for your terminal!)
  10963. alias excuses='echo `telnet bofh.jeffballard.us 666 2>/dev/null` |grep --color -o "Your excuse is:.*$"'     # excuses
  10964. alias freechess='telnet fics.freechess.org 5000'                        # connects to a telnet server for free internet chess
  10965. alias funfacts='wget http://www.randomfunfacts.com -O - 2>/dev/null | grep \<strong\> | sed "s;^.*<i>\(.*\)</i>.*$;\1;";'
  10966. alias funknet='telnet the-funk.net 7000'                            # Access to Funk.net
  10967. alias futurama='curl -Is slashdot.org | sed -n '5p' | sed 's/^X-//''                # get Futurama quotations from slashdot.org servers
  10968. alias guitartune='for n in E2 A2 D3 G3 B3 E4;do play -n synth 4 pluck $n repeat 2;done'     # tune your guitar from the command line
  10969. alias iamcow='fortune | cowsay'
  10970. alias iamsurprise='fortune | cowsay -f $(random_cow)'
  10971. alias insults='wget http://www.randominsults.net -O - 2>/dev/null | grep \<strong\> | sed "s;^.*<i>\(.*\)</i>.*$;\1;";'
  10972. alias lotto='shuf -i 1-49 -n 6 | sort -n | xargs'                       # lotto generator
  10973. alias matrix='echo -e "\e[32m"; while :; do for i in {1..16}; do r="$(($RANDOM % 2))"; if [[ $(($RANDOM % 5)) == 1 ]]; then if [[ $(($RANDOM % 4)) == 1 ]]; then v+="\e[1m $r   "; else v+="\e[2m $r   "; fi; else v+="     "; fi; done; echo -e "$v"; v=""; done'
  10974. alias matrix2='echo -e "\e[31m"; while $t; do for i in `seq 1 30`;do r="$[($RANDOM % 2)]";h="$[($RANDOM % 4)]";if [ $h -eq 1 ]; then v="\e[1m $r";else v="\e[2m $r";fi;v2="$v2 $v";done;echo -e $v2;v2="";done;'
  10975. alias matrix3='COL=$(( $(tput cols) / 2 )); clear; tput setaf 2; while :; do tput cup $((RANDOM%COL)) $((RANDOM%COL)); printf "%$((RANDOM%COL))s" $((RANDOM%2)); done'
  10976. alias matrix4='echo -ne "\e[32m" ; while true ; do echo -ne "\e[$(($RANDOM % 2 + 1))m" ; tr -c "[:print:]" " " < /dev/urandom | dd count=1 bs=50 2> /dev/null ; done'
  10977. alias matrix5='tr -c "[:digit:]" " " < /dev/urandom | dd cbs=$COLUMNS conv=lcase,unblock | GREP_COLOR="1;32" grep --color "[^ ]"'
  10978. alias roulette='[ $[ $RANDOM % 6 ] == 0 ] && echo Die || echo Live'             # command line Russian roulette
  10979. alias starwars='telnet towel.blinkenlights.nl'                          # the famous starwars ASCII version from telnet
  10980. alias termvideo_bw='mplayer -vo aa'                             # watch movies in ASCII (just direct to the video)
  10981. alias termvideo='mplayer -vo caca'                              # watch movies in ASCII (just direct to the video)
  10982. alias wooters='telnet zerocarbs.wooters.us'                         # connects to a telnet service monitoring Woot (Gives you an updating woot! item tracker!)
  10983.  
  10984.  
  10985.  
  10986. ##################################################
  10987. # Network/Internet -oriented stuff       #
  10988. ##################################################
  10989.  
  10990. alias appson="netstat -lantp | grep -i stab | awk -F/ '{print $2}' | sort | uniq"   # view only the process name using an internet connection
  10991. alias bandwidth='dd if=/dev/zero of=/dev/null bs=1M count=32768'            # processor / memory bandwidthd? in GB/s
  10992. alias browse_bonjour='dns-sd -B'                            # browse services advertised via Bonjour
  10993. # alias daemons='ls /var/run/daemons'                           # daemon managment (ommited for function)
  10994. alias dbdumpcp='scp -P 1234 username@12.34.56.78:$HOME/Backup/www/data/someSite/db.sql $HOME/Backup/data/db.sql'    # copy remote db to local
  10995. alias dns='cat /etc/resolv.conf'                            # view DNS numbers
  10996. alias domain2ban='~/.scripts/Domain2Ban.sh'
  10997. alias estab='ss -p | grep STA'                              # view only established sockets (fails if "ss" is screensaver alias)
  10998. alias finchsync='java -jar ~/finchsync/finchsync.jar'                   # start FinchSync Admin
  10999. # alias ftop='watch -d -n 2 'df; ls -FlAt;''                        # like top, but for files
  11000. alias hdinfo='hdparm -i[I] /dev/sda'                            # hard disk information - model/serial no.
  11001. alias hostip='wget http://checkip.dyndns.org/ -O - -o /dev/null | cut -d: -f 2 | cut -d\< -f 1'
  11002. alias hostname_lookup='lookupd -d'                          # interactive debugging mode for lookupd (use tab-completion)
  11003. alias http_trace='pkt_trace port 80'                            # to show all HTTP packets
  11004. alias iftop='sudo iftop -i eth0'                            # start "iftop" program (sudo apt-get install iftop)
  11005. alias ip4grep="grep -E '([0-9]{1,3}\.){3}[0-9]{1,3}'"                   # look for IPv4 address in files
  11006. alias ip='curl www.whatismyip.org'
  11007. alias ip_info='ipconfig getpacket en1'                          # info on DHCP server, router, DNS server, etc (for en0 or en1)
  11008. alias ipt80='sudo iptstate -D 80'                           # check out only iptables state of http port 80 (requires iptstate)
  11009. alias ip_trace='pkt_trace ip'                               # to show all IP packets
  11010. alias ipttrans='sudo iptstate -D 51413'                         # iptables state of Transmission-Daemon port (requires iptstate)
  11011. alias listen='sudo netstat -pnutl'                          # lists all listening ports together with PID of associated process
  11012. alias lsock='sudo /usr/sbin/lsof -i -P'                         # to display open sockets ( -P option to lsof disables port names)
  11013. alias memrel='free && sync && echo 3 > /proc/sys/vm/drop_caches && free'        # release memory used by the Linux kernel on caches
  11014. alias net1='watch --interval=2 "sudo netstat -apn -l -A inet"'
  11015. alias net2='watch --interval=2 "sudo netstat -anp --inet --inet6"'
  11016. alias net3='sudo lsof -i'
  11017. alias net4='watch --interval=2 "sudo netstat -p -e --inet --numeric-hosts"'
  11018. alias net5='watch --interval=2 "sudo netstat -tulpan"'
  11019. alias net6='sudo netstat -tulpan'
  11020. alias net7='watch --interval=2 "sudo netstat -utapen"'
  11021. alias net8='watch --interval=2 "sudo netstat -ano -l -A inet"'
  11022. alias netapps="lsof -P -i -n | cut -f 1 -d ' '| uniq | tail -n +2"
  11023. alias nethogs='sudo nethogs eth0'                           # start "nethogs" program (sudo apt-get install nethogs)
  11024. alias netl='sudo nmap -sT -O localhost'
  11025. alias netscan='sudo iwlist wlan0 scan'                          # to scan your environment for available networks, do the following
  11026. alias netstats='sudo iwspy wlan0'                           # if card supports it, you can collect wireless statistics by using
  11027. alias network='sudo lshw -C network'                            # view network device info
  11028. alias networkdump='sudo tcpdump not port 22'                        # dump all the network activity except ssh stuff
  11029. alias nsl='netstat -f inet | grep -v CLOSE_WAIT | cut -c-6,21-94 | tail +2'     # show all programs connected or listening on a network port
  11030. alias ns='netstat -alnp --protocol=inet | grep -v CLOSE_WAIT | cut -c-6,21-94 | tail +2'
  11031. alias openports='sudo netstat -nape --inet'                         # view open ports
  11032. alias pkt_trace='sudo tcpflow -i `active_net_iface` -c'
  11033. alias ports='lsof -i -n -P'                                 # view programs using an internet connection
  11034. alias portstats='sudo netstat -s'                           # show statistics for all ports
  11035. alias proxy1='ssh -p 1234 -D 5678 username@12.34.56.78'                 # SOCKS proxy - these anonomise browsing - 12.34.56.78
  11036. alias proxy2='ssh -p 8765 -D 4321 username@87.65.43.21'                 # SOCKS proxy - these anonomise browsing - 87.65.43.21
  11037. alias ramvalue='sudo dd if=/dev/mem | cat | strings'                    # will show you all the string (plain text) values in ram
  11038. alias randommac='python -c "from itertools import imap; from random import randint; print ':'.join(['%02x'%x for x in imap(lambda x:randint(0,255), range(6))])"'                                       # generate random valid mac addresses
  11039. alias remote='ssh -p 1234 12.34.56.78'                          # access some remote host
  11040. alias restartnet='sudo /etc/rc.d/network restart;sudo /etc/rc.d/wicd restart'
  11041. alias rssup='php /srv/http/rssupdate.php'
  11042. alias setessid='sudo iwconfig wlan0 essid network-essid'                # set the essid, which identifies the network access point you want
  11043. alias smtp_trace='pkt_trace port smtp'                          # to show all SMTP packets
  11044. alias someDBdump='sudo mysqldump someDB -uroot -p > $HOME/www/_dbs/someDB.sql'
  11045. alias spavr='gtkterm -c avr'
  11046. # alias spavr='sudo chmod a=rw /dev/ttyUSB0; gtkterm -c avr'
  11047. alias spk800i='gtkterm -c k800i'
  11048. # alias spk800i='sudo chmod a=rw /dev/rfcomm0; gtkterm -c k800i'
  11049. alias sync='java -jar ~/finchsync/finchsync.jar -nogui'                 # sync to PDA .. well, that'll be a sync then! - start FinchSync SVR
  11050. alias syncoff='java -jar ~/Apps/FinchSync/finchsync.jar -stopserver'            # sync to PDA .. well, that'll be a sync then! - stop FinchSync SVR
  11051. alias tcpstats='sudo netstat -st'                           # show statistics for tcp ports
  11052. alias tcp_='sudo netstat -atp'                              # list all TCP ports
  11053. alias tcp_trace='pkt_trace tcp'                             # to show all TCP packets
  11054. alias topsites='curl -s -O http://s3.amazonaws.com/alexa-static/top-1m.csv.zip ; unzip -q -o top-1m.csv.zip top-1m.csv ; head -1000 top-1m.csv | cut -d, -f2 | cut -d/ -f1 > topsites.txt'                          # get a list of top 1000 sites from alexa
  11055. alias tproxy='ssh -ND 8118 user@server&; export LD_PRELOAD="/usr/lib/libtsocks.so"' # creates a proxy based on tsocks
  11056. alias udpstats='sudo netstat -su'                           # show statistics for udp ports
  11057. alias udp='sudo netstat -aup'                               # list all UDP ports
  11058. alias udp_trace='pkt_trace udp'                             # to show all UDP packets
  11059. alias uploads='cd /some/folder'                             # access some folder
  11060. alias vncup='x11vnc -nopw -ncache 10 -display :0 -localhost'
  11061. alias website_dl='wget --random-wait -r -p -e robots=off -U mozilla "$1"'       # download an entire website
  11062. alias website_images='wget -r -l1 --no-parent -nH -nd -P/tmp -A".gif,.jpg" "$1"'    # download all images from a site
  11063. alias whois='whois -H'
  11064. alias wscan='iwlist scan'                               # terminal network scan for wireless signals
  11065. alias wwwmirror2='wget -k -r -l ${2} ${1}'                      # wwwmirror2 usage: wwwmirror2 [level] [site_url]
  11066. alias wwwmirror='wget -ErkK -np ${1}'
  11067.  
  11068.  
  11069.  
  11070. ##################################################
  11071. # Package making and installation        #
  11072. ##################################################
  11073.  
  11074. alias checkinstall-force='sudo checkinstall --dpkgflags "--force-overwrite"'
  11075. alias checkinstall-noinstall='sudo checkinstall -y --fstrans=no --install=no'
  11076. alias checkinstall='sudo checkinstall -y --fstrans=no'
  11077. alias debinstall-force='sudo dpkg -i --force-overwrite'
  11078. alias debinstall='sudo dpkg -i'
  11079. alias diffinstall='diff /tmp/install.pre /tmp/install.pos | grep \"^>\" | sed \"s/^> //g\"' # run diffinstall fourth, after diffinstall to show what files were copied in your system
  11080. alias postinstall='sudo find / ! \( -path /proc -prune -o -path /tmp -prune -o -path /dev -prune -o -path /mnt -prune \) > /tmp/install.pos'    # run postinstall third, after "make install"
  11081. alias preinstall='sudo find / ! \( -path /proc -prune -o -path /tmp -prune -o -path /dev -prune -o -path /mnt -prune \) > /tmp/install.pre' # run preinstall first, then "make install"
  11082.  
  11083.  
  11084.  
  11085. ##################################################
  11086. # Permissions                    #
  11087. ##################################################
  11088.  
  11089. alias 000='chmod 000'
  11090. alias 640='chmod 640'
  11091. alias 644='chmod 644'
  11092. alias 755='chmod 755'
  11093. alias 775='chmod 775'
  11094. alias mx='chmod a+x'
  11095. alias perm='stat --printf "%a %n \n "'                              # requires a file name e.g. perm file
  11096. alias restoremod='chgrp users -R .;chmod u=rwX,g=rX,o=rX -R .;chown $(pwd |cut -d / -f 3) -R .' # restore user,group and mod of an entire website
  11097.  
  11098.  
  11099.  
  11100. ##################################################
  11101. # Personal help                  #
  11102. ##################################################
  11103.  
  11104. alias a?='cat ~/.alias.help'
  11105. alias dn='OPTIONS=$(\ls -F | grep /$); select s in $OPTIONS; do cd $PWD/$s; break;done'
  11106. alias espanol='echo -e \"á Á é É í Í ó Ó ú Ú ñ Ñ ü Ü ¿ ¡ ¢ ‘ ’ “ ” „ ‚ …\"'
  11107. alias f?='cat ~/.function.help'
  11108. alias help='OPTIONS=$(\ls ~/.tips -F);select s in $OPTIONS; do less ~/.tips/$s; break;done'
  11109. alias testh='help test|sed -e :a -e "$!N;s/\(-n STRING\)\n/\1, /;s/\n\( \{23\}\| \{4\}\([a-z]\)\)/ \2/;ta;P;D"|sed "s/ \{1,\}/ /g;/^ $/d;/:$/s/^/\n/"|sed -n "/File operators:/,\$p"'               # test quick help alias
  11110.  
  11111.  
  11112.  
  11113. ##################################################
  11114. # Secure-delete substitution             #
  11115. ##################################################
  11116.  
  11117. alias sfill-freespace='sudo sfill -I -l -l -v'
  11118. alias sfill-f='sudo sfill -f -l -l -v -z'
  11119. alias sfill='sudo sfill -l -l -v -z'
  11120. alias sfill-usedspace='sudo sfill -i -l -l -v'
  11121. alias smem-f='sudo sdmem -f -l -l -v'
  11122. alias smem-secure='sudo sdmem -v'
  11123. alias smem='sudo sdmem -l -l -v'
  11124. alias srm-m='sudo srm -f -m -z -v'
  11125. alias srm='sudo srm -f -s -z -v'
  11126. alias sswap-sda5='sudo sswap -f -l -l -v -z /dev/sda5'
  11127. alias sswap='sudo sswap -f -l -l -v -z'
  11128. alias swapoff='sudo swapoff /dev/sda5'
  11129. alias swapon='sudo swapon /dev/sda5'
  11130.  
  11131.  
  11132.  
  11133. ##################################################
  11134. # Set up auto extension stuff            #
  11135. ##################################################
  11136.  
  11137. ###### If -s flags present, define suffix alias: if command word on command line is in form `text.name',
  11138. # where text is any non-empty string, its replaced by text 'value text.name'. Note that names treated as literal
  11139. # string, not pattern.  A trailing space in value is not special in this case. For example, alias -s ps=gv
  11140. # will cause command `*.ps' to be expanded to `gv *.ps'. As alias expansion is carried out earlier than globbing,
  11141. # `*.ps' will then be expanded. Suffix aliases constitute different name space from other aliases (so in above
  11142. # example its still possible to create alias for command ps) and two sets are never listed together.
  11143. # alias -s avi=mplayer
  11144. # alias -s bz2=tar -xjvf
  11145. # alias -s com=$BROWSER
  11146. # alias -s cpp=vim
  11147. # alias -s doc=soffice
  11148. # alias -s eps=eog
  11149. # alias -s gif=eog
  11150. # alias -s gz=tar -xzvf
  11151. # alias -s html=$BROWSER
  11152. # alias -s img=mplayer
  11153. # alias -s install=$EDITOR
  11154. # alias -s iso=mplayer
  11155. # alias -s java=$EDITOR
  11156. # alias -s jpg=eog
  11157. # alias -s mkv=mplayer
  11158. # alias -s mp3=mplayer
  11159. # alias -s mpeg=mplayer
  11160. # alias -s mpg=mplayer
  11161. # alias -s mws=maple
  11162. # alias -s net=$BROWSER
  11163. # alias -s odt=soffice
  11164. # alias -s org=$BROWSER
  11165. # alias -s pdf=evince
  11166. # alias -s php=$BROWSER
  11167. # alias -s PKGBUILD=vim
  11168. # alias -s png=eog
  11169. # alias -s ppt=soffice
  11170. # alias -s ps=gv
  11171. # alias -s se=$BROWSER
  11172. # alias -s sh=vim
  11173. # alias -s sxw=soffice
  11174. # alias -s tex=$EDITOR
  11175. # alias -s txt=$EDITOR
  11176. # alias -s wmv=mplayer
  11177. # alias -s xls=soffice
  11178.  
  11179.  
  11180.  
  11181. ##################################################
  11182. # Shred substitution                 #
  11183. ##################################################
  11184.  
  11185. alias shred-sda-r='sudo shred -v -z -n 1 /dev/sda'
  11186. alias shred-sda='sudo shred -v -z -n 0 /dev/sda'
  11187. alias shred-sdb-r='sudo shred -v -z -n 1 /dev/sdb'
  11188. alias shred-sdb='sudo shred -v -z -n 0 /dev/sdb'
  11189. alias shred-sdc-r='sudo shred -v -z -n 1 /dev/sdc'
  11190. alias shred-sdc='sudo shred -v -z -n 0 /dev/sdc'
  11191. alias shred-sdd-r='sudo shred -v -z -n 1 /dev/sdd'
  11192. alias shred-sdd='sudo shred -v -z -n 0 /dev/sdd'
  11193. alias shred-sde-r='sudo shred -v -z -n 1 /dev/sde'
  11194. alias shred-sde='sudo shred -v -z -n 0 /dev/sde'
  11195. alias shred-sdf-r='sudo shred -v -z -n 1 /dev/sdf'
  11196. alias shred-sdf='sudo shred -v -z -n 0 /dev/sdf'
  11197. alias shred-sdg-r='sudo shred -v -z -n 1 /dev/sdg'
  11198. alias shred-sdg='sudo shred -v -z -n 0 /dev/sdg'
  11199.  
  11200.  
  11201.  
  11202. ##################################################
  11203. # Xterm and Aterm                #
  11204. ##################################################
  11205.  
  11206. alias aterm='xterm -ls -fg gray -bg black'
  11207. alias termb='xterm -bg AntiqueWhite -fg NavyBlue &'
  11208. alias termg='xterm -bg AntiqueWhite -fg OliveDrab &'
  11209. alias termr='xterm -bg AntiqueWhite -fg DarkRed &'
  11210. alias term='xterm -bg AntiqueWhite -fg Black &'
  11211. alias xsu='xterm -fn 7x14 -bg DarkOrange4 -fg white -e su &'
  11212. alias xtop='xterm -fn 6x13 -bg LightSlateGray -fg black -e top &'
  11213.  
  11214.  
  11215.  
  11216. ##################################################
  11217. ##################################################
  11218. ##################################################
  11219.  
  11220.  
  11221.  
  11222.  
  11223.  
  11224.  
  11225.  
  11226.  
  11227. ######################################################################################################################################################
  11228. #----- BASHRC ENDS HERE ------ BASHRC ENDS HERE ------ BASHRC ENDS HERE ------ BASHRC ENDS HERE ------ BASHRC ENDS HERE ------ BASHRC ENDS HERE ------
  11229. ######################################################################################################################################################
  11230.  
  11231.  
  11232.  
  11233.  
  11234.  
  11235.  
  11236.  
  11237.  
  11238. fi  # end interactive check
  11239.  
  11240.  
  11241.  
  11242.  
  11243.  
  11244.  
  11245.  
  11246.  
  11247. ######################################################################################################################################################
  11248. ################################### MY BASHRC FILE ################################### MY BASHRC FILE ################################### MY BASHRC FILE
  11249. ######################################################################################################################################################
Add Comment
Please, Sign In to add comment