SHARE
TWEET

ultimate bashrc

a guest Jan 16th, 2011 4,095 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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