lexthebrony

bashrc

Nov 12th, 2014
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 27.34 KB | None | 0 0
  1. #Calls bash_aliases for custom definitions
  2.  
  3. if [ -f $HOME/.bash_aliases ]
  4. then
  5.   . $HOME/.bash_aliases
  6. fi
  7.  
  8. # =============================================================== #
  9. #
  10. #
  11. # By Emmanuel Rouat with some minor flavoring from Noah B.
  12. #
  13. # Last modified: Wed Nov 12 01:01:47 EST 2014
  14.  
  15. #  This file is normally read by interactive shells only.
  16. #+ Here is the place to define your aliases, functions and
  17. #+ other interactive features like your prompt.
  18. #
  19. #  The majority of the code here assumes you are on a GNU
  20. #+ system (most likely a Linux box) and is often based on code
  21. #+ found on Usenet or Internet.
  22. #
  23. #  See for instance:
  24. #  http://tldp.org/LDP/abs/html/index.html
  25. #  http://www.caliban.org/bash
  26. #  http://www.shelldorado.com/scripts/categories.html
  27. #  http://www.dotfiles.org
  28. #
  29. #  The choice of colors was done for a shell with a dark background
  30. #+ (white on black), and this is usually also suited for pure text-mode
  31. #+ consoles (no X server available). If you use a white background,
  32. #+ you'll have to do some other choices for readability.
  33. #
  34. #  This bashrc file is a bit overcrowded.
  35. #  Remember, it is just just an example.
  36. #  Tailor it to your needs.
  37. #
  38. # =============================================================== #
  39.  
  40. # --> Comments added by HOWTO author.
  41.  
  42. # If not running interactively, don't do anything
  43. [ -z "$PS1" ] && return
  44.  
  45.  
  46. #-------------------------------------------------------------
  47. # Source global definitions (if any)
  48. #-------------------------------------------------------------
  49.  
  50.  
  51. if [ -f /etc/bashrc ]; then
  52.       . /etc/bashrc   # --> Read /etc/bashrc, if present.
  53. fi
  54.  
  55.  
  56. #--------------------------------------------------------------
  57. #  Automatic setting of $DISPLAY (if not set already).
  58. #  This works for me - your mileage may vary. . . .
  59. #  The problem is that different types of terminals give
  60. #+ different answers to 'who am i' (rxvt in particular can be
  61. #+ troublesome) - however this code seems to work in a majority
  62. #+ of cases.
  63. #--------------------------------------------------------------
  64.  
  65. function get_xserver ()
  66. {
  67.     case $TERM in
  68.         xterm )
  69.             XSERVER=$(who am i | awk '{print $NF}' | tr -d ')''(' )
  70.             # Ane-Pieter Wieringa suggests the following alternative:
  71.             #  I_AM=$(who am i)
  72.             #  SERVER=${I_AM#*(}
  73.             #  SERVER=${SERVER%*)}
  74.             XSERVER=${XSERVER%%:*}
  75.             ;;
  76.             aterm | rxvt)
  77.             # Find some code that works here. ...
  78.             ;;
  79.     esac
  80. }
  81.  
  82. if [ -z ${DISPLAY:=""} ]; then
  83.     get_xserver
  84.     if [[ -z ${XSERVER}  || ${XSERVER} == $(hostname) ||
  85.        ${XSERVER} == "unix" ]]; then
  86.           DISPLAY=":0.0"          # Display on local host.
  87.     else
  88.        DISPLAY=${XSERVER}:0.0     # Display on remote host.
  89.     fi
  90. fi
  91.  
  92. export DISPLAY
  93.  
  94. #-------------------------------------------------------------
  95. # Some settings
  96. #-------------------------------------------------------------
  97.  
  98. #set -o nounset     # These  two options are useful for debugging.
  99. #set -o xtrace
  100. alias debug="set -o nounset; set -o xtrace"
  101.  
  102. ulimit -S -c 0      # Don't want coredumps.
  103. set -o notify
  104. set -o noclobber
  105. set -o ignoreeof
  106.  
  107.  
  108. # Enable options:
  109. shopt -s cdspell
  110. shopt -s cdable_vars
  111. shopt -s checkhash
  112. shopt -s checkwinsize
  113. shopt -s sourcepath
  114. shopt -s no_empty_cmd_completion
  115. shopt -s cmdhist
  116. shopt -s histappend histreedit histverify
  117. shopt -s extglob       # Necessary for programmable completion.
  118.  
  119. # Disable options:
  120. shopt -u mailwarn
  121. unset MAILCHECK        # Don't want my shell to warn me of incoming mail.
  122.  
  123.  
  124. #-------------------------------------------------------------
  125. # Greeting, motd etc. ...
  126. #-------------------------------------------------------------
  127.  
  128. # Color definitions (taken from Color Bash Prompt HowTo).
  129. # Some colors might look different of some terminals.
  130. # For example, I see 'Bold Red' as 'orange' on my screen,
  131. # hence the 'Green' 'BRed' 'Red' sequence I often use in my prompt.
  132.  
  133.  
  134. # Normal Colors
  135. Black='\e[0;30m'        # Black
  136. Red='\e[0;31m'          # Red
  137. Green='\e[0;32m'        # Green
  138. Yellow='\e[0;33m'       # Yellow
  139. Blue='\e[0;34m'         # Blue
  140. Purple='\e[0;35m'       # Purple
  141. Cyan='\e[0;36m'         # Cyan
  142. White='\e[0;37m'        # White
  143.  
  144. # Bold
  145. BBlack='\e[1;30m'       # Black
  146. BRed='\e[1;31m'         # Red
  147. BGreen='\e[1;32m'       # Green
  148. BYellow='\e[1;33m'      # Yellow
  149. BBlue='\e[1;34m'        # Blue
  150. BPurple='\e[1;35m'      # Purple
  151. BCyan='\e[1;36m'        # Cyan
  152. BWhite='\e[1;37m'       # White
  153.  
  154. # Background
  155. On_Black='\e[40m'       # Black
  156. On_Red='\e[41m'         # Red
  157. On_Green='\e[42m'       # Green
  158. On_Yellow='\e[43m'      # Yellow
  159. On_Blue='\e[44m'        # Blue
  160. On_Purple='\e[45m'      # Purple
  161. On_Cyan='\e[46m'        # Cyan
  162. On_White='\e[47m'       # White
  163.  
  164. NC="\e[m"               # Color Reset
  165.  
  166.  
  167. ALERT=${BWhite}${On_Red} # Bold White on red background
  168.  
  169.  
  170.  
  171. echo -e "${BCyan}This is BASH ${BRed}${BASH_VERSION%.*}${BCyan}\
  172. - DISPLAY on ${BRed}$DISPLAY${NC}\n"
  173. date
  174. if [ -x /usr/games/fortune ]; then
  175.     /usr/games/fortune -s     # Makes our day a bit more fun.... :-)
  176. fi
  177.  
  178. function _exit()              # Function to run upon exit of shell.
  179. {
  180.     echo -e "${BRed}Hasta la vista, baby${NC}"
  181. }
  182. trap _exit EXIT
  183.  
  184. #-------------------------------------------------------------
  185. # Shell Prompt - for many examples, see:
  186. #       http://www.debian-administration.org/articles/205
  187. #       http://www.askapache.com/linux/bash-power-prompt.html
  188. #       http://tldp.org/HOWTO/Bash-Prompt-HOWTO
  189. #       https://github.com/nojhan/liquidprompt
  190. #-------------------------------------------------------------
  191. # Current Format: [TIME USER@HOST PWD] >
  192. # TIME:
  193. #    Green     == machine load is low
  194. #    Orange    == machine load is medium
  195. #    Red       == machine load is high
  196. #    ALERT     == machine load is very high
  197. # USER:
  198. #    Cyan      == normal user
  199. #    Orange    == SU to user
  200. #    Red       == root
  201. # HOST:
  202. #    Cyan      == local session
  203. #    Green     == secured remote connection (via ssh)
  204. #    Red       == unsecured remote connection
  205. # PWD:
  206. #    Green     == more than 10% free disk space
  207. #    Orange    == less than 10% free disk space
  208. #    ALERT     == less than 5% free disk space
  209. #    Red       == current user does not have write privileges
  210. #    Cyan      == current filesystem is size zero (like /proc)
  211. # >:
  212. #    White     == no background or suspended jobs in this shell
  213. #    Cyan      == at least one background job in this shell
  214. #    Orange    == at least one suspended job in this shell
  215. #
  216. #    Command is added to the history file each time you hit enter,
  217. #    so it's available to all shells (using 'history -a').
  218.  
  219.  
  220. # Test connection type:
  221. if [ -n "${SSH_CONNECTION}" ]; then
  222.     CNX=${Green}        # Connected on remote machine, via ssh (good).
  223. elif [[ "${DISPLAY%%:0*}" != "" ]]; then
  224.     CNX=${ALERT}        # Connected on remote machine, not via ssh (bad).
  225. else
  226.     CNX=${BCyan}        # Connected on local machine.
  227. fi
  228.  
  229. # Test user type:
  230. if [[ ${USER} == "root" ]]; then
  231.     SU=${Red}           # User is root.
  232. elif [[ ${USER} != $(logname) ]]; then
  233.     SU=${BRed}          # User is not login user.
  234. else
  235.     SU=${BCyan}         # User is normal (well ... most of us are).
  236. fi
  237.  
  238.  
  239.  
  240. NCPU=$(grep -c 'processor' /proc/cpuinfo)    # Number of CPUs
  241. SLOAD=$(( 100*${NCPU} ))        # Small load
  242. MLOAD=$(( 200*${NCPU} ))        # Medium load
  243. XLOAD=$(( 400*${NCPU} ))        # Xlarge load
  244.  
  245. # Returns system load as percentage, i.e., '40' rather than '0.40)'.
  246. function load()
  247. {
  248.     local SYSLOAD=$(cut -d " " -f1 /proc/loadavg | tr -d '.')
  249.     # System load of the current host.
  250.     echo $((10#$SYSLOAD))       # Convert to decimal.
  251. }
  252.  
  253. # Returns a color indicating system load.
  254. function load_color()
  255. {
  256.     local SYSLOAD=$(load)
  257.     if [ ${SYSLOAD} -gt ${XLOAD} ]; then
  258.         echo -en ${ALERT}
  259.     elif [ ${SYSLOAD} -gt ${MLOAD} ]; then
  260.         echo -en ${Red}
  261.     elif [ ${SYSLOAD} -gt ${SLOAD} ]; then
  262.         echo -en ${BRed}
  263.     else
  264.         echo -en ${Green}
  265.     fi
  266. }
  267.  
  268. # Returns a color according to free disk space in $PWD.
  269. function disk_color()
  270. {
  271.     if [ ! -w "${PWD}" ] ; then
  272.         echo -en ${Red}
  273.         # No 'write' privilege in the current directory.
  274.     elif [ -s "${PWD}" ] ; then
  275.         local used=$(command df -P "$PWD" |
  276.                    awk 'END {print $5} {sub(/%/,"")}')
  277.         if [ ${used} -gt 95 ]; then
  278.             echo -en ${ALERT}           # Disk almost full (>95%).
  279.         elif [ ${used} -gt 90 ]; then
  280.             echo -en ${BRed}            # Free disk space almost gone.
  281.         else
  282.             echo -en ${Green}           # Free disk space is ok.
  283.         fi
  284.     else
  285.         echo -en ${Cyan}
  286.         # Current directory is size '0' (like /proc, /sys etc).
  287.     fi
  288. }
  289.  
  290. # Returns a color according to running/suspended jobs.
  291. function job_color()
  292. {
  293.     if [ $(jobs -s | wc -l) -gt "0" ]; then
  294.         echo -en ${BRed}
  295.     elif [ $(jobs -r | wc -l) -gt "0" ] ; then
  296.         echo -en ${BCyan}
  297.     fi
  298. }
  299.  
  300. # Adds some text in the terminal frame (if applicable).
  301.  
  302.  
  303. # Now we construct the prompt.
  304. PROMPT_COMMAND="history -a"
  305. case ${TERM} in
  306.   *term | rxvt | linux)
  307.         PS1="\[\$(load_color)\][\A\[${NC}\] "
  308.         # Time of day (with load info):
  309.         PS1="\[\$(load_color)\][\A\[${NC}\] "
  310.         # User@Host (with connection type info):
  311.         PS1=${PS1}"\[${SU}\]\u\[${NC}\]@\[${CNX}\]\h\[${NC}\] "
  312.         # PWD (with 'disk space' info):
  313.         PS1=${PS1}"\[\$(disk_color)\]\W]\[${NC}\] "
  314.         # Prompt (with 'job' info):
  315.         PS1=${PS1}"\[\$(job_color)\]>\[${NC}\] "
  316.         # Set title of current xterm:
  317.         PS1=${PS1}"\[\e]0;[\u@\h] \w\a\]"
  318.         ;;
  319.     *)
  320.         PS1="(\A \u@\h \W) > " # --> PS1="(\A \u@\h \w) > "
  321.                                # --> Shows full pathname of current dir.
  322.         ;;
  323. esac
  324.  
  325.  
  326.  
  327. export TIMEFORMAT=$'\nreal %3R\tuser %3U\tsys %3S\tpcpu %P\n'
  328. export HISTIGNORE="&:bg:fg:ll:h"
  329. export HISTTIMEFORMAT="$(echo -e ${BCyan})[%d/%m %H:%M:%S]$(echo -e ${NC}) "
  330. export HISTCONTROL=ignoredups
  331. export HOSTFILE=$HOME/.hosts    # Put a list of remote hosts in ~/.hosts
  332.  
  333.  
  334. #============================================================
  335. #
  336. #  ALIASES AND FUNCTIONS
  337. #
  338. #  Arguably, some functions defined here are quite big.
  339. #  If you want to make this file smaller, these functions can
  340. #+ be converted into scripts and removed from here.
  341. #
  342. #============================================================
  343.  
  344. #-------------------
  345. # Personnal Aliases
  346. #-------------------
  347.  
  348. #alias rm='rm -i'
  349. #alias cp='cp -i'
  350. #alias mv='mv -i'
  351. # -> Prevents accidentally clobbering files.
  352. alias mkdir='mkdir -p'
  353.  
  354. alias h='history'
  355. alias j='jobs -l'
  356. alias which='type -a'
  357. alias ..='cd ..'
  358.  
  359. # Pretty-print of some PATH variables:
  360. alias path='echo -e ${PATH//:/\\n}'
  361. alias libpath='echo -e ${LD_LIBRARY_PATH//:/\\n}'
  362.  
  363.  
  364. alias du='du -kh'    # Makes a more readable output.
  365. alias df='df -kTh'
  366.  
  367. #-------------------------------------------------------------
  368. # The 'ls' family (this assumes you use a recent GNU ls).
  369. #-------------------------------------------------------------
  370. # Add colors for filetype and  human-readable sizes by default on 'ls':
  371. alias ls='ls -h --color'
  372. alias lx='ls -lXB'         #  Sort by extension.
  373. alias lk='ls -lSr'         #  Sort by size, biggest last.
  374. alias lt='ls -ltr'         #  Sort by date, most recent last.
  375. alias lc='ls -ltcr'        #  Sort by/show change time,most recent last.
  376. alias lu='ls -ltur'        #  Sort by/show access time,most recent last.
  377.  
  378. # The ubiquitous 'll': directories first, with alphanumeric sorting:
  379. alias ll="ls -lv --group-directories-first"
  380. alias lm='ll |more'        #  Pipe through 'more'
  381. alias lr='ll -R'           #  Recursive ls.
  382. alias la='ll -A'           #  Show hidden files.
  383. alias tree='tree -Csuh'    #  Nice alternative to 'recursive ls' ...
  384.  
  385.  
  386. #-------------------------------------------------------------
  387. # Tailoring 'less'
  388. #-------------------------------------------------------------
  389.  
  390. #alias more='less'
  391. export PAGER=less
  392. export LESSCHARSET='latin1'
  393. export LESSOPEN='|/usr/bin/lesspipe.sh %s 2>&-'
  394.                 # Use this if lesspipe.sh exists.
  395. export LESS='-i -N -w  -z-4 -g -e -M -X -F -R -P%t?f%f \
  396. :stdin .?pb%pb\%:?lbLine %lb:?bbByte %bb:-...'
  397.  
  398. # LESS man page colors (makes Man pages more readable).
  399. export LESS_TERMCAP_mb=$'\E[01;31m'
  400. export LESS_TERMCAP_md=$'\E[01;31m'
  401. export LESS_TERMCAP_me=$'\E[0m'
  402. export LESS_TERMCAP_se=$'\E[0m'
  403. export LESS_TERMCAP_so=$'\E[01;44;33m'
  404. export LESS_TERMCAP_ue=$'\E[0m'
  405. export LESS_TERMCAP_us=$'\E[01;32m'
  406.  
  407.  
  408. #-------------------------------------------------------------
  409. # Spelling typos - highly personnal and keyboard-dependent :-)
  410. #-------------------------------------------------------------
  411.  
  412. alias xs='cd'
  413. alias vf='cd'
  414. alias moer='more'
  415. alias moew='more'
  416. alias kk='ll'
  417.  
  418.  
  419. #-------------------------------------------------------------
  420. # A few fun ones
  421. #-------------------------------------------------------------
  422.  
  423. # Adds some text in the terminal frame (if applicable).
  424.  
  425. function xtitle()
  426. {
  427.     case "$TERM" in
  428.     *term* | rxvt)
  429.         echo -en  "\e]0;$*\a" ;;
  430.     *)  ;;
  431.     esac
  432. }
  433.  
  434.  
  435. # Aliases that use xtitle
  436. alias top='xtitle Processes on $HOST && top'
  437. alias make='xtitle Making $(basename $PWD) ; make'
  438.  
  439. # .. and functions
  440. function man()
  441. {
  442.     for i ; do
  443.         xtitle The $(basename $1|tr -d .[:digit:]) manual
  444.         command man -a "$i"
  445.     done
  446. }
  447.  
  448.  
  449. #-------------------------------------------------------------
  450. # Make the following commands run in background automatically:
  451. #-------------------------------------------------------------
  452.  
  453. function te()  # wrapper around xemacs/gnuserv
  454. {
  455.     if [ "$(gnuclient -batch -eval t 2>&-)" == "t" ]; then
  456.        gnuclient -q "$@";
  457.     else
  458.        ( xemacs "$@" &);
  459.     fi
  460. }
  461.  
  462. function soffice() { command soffice "$@" & }
  463. function firefox() { command firefox "$@" & }
  464. function xpdf() { command xpdf "$@" & }
  465.  
  466.  
  467. #-------------------------------------------------------------
  468. # File & strings related functions:
  469. #-------------------------------------------------------------
  470.  
  471.  
  472. # Find a file with a pattern in name:
  473. function ff() { find . -type f -iname '*'"$*"'*' -ls ; }
  474.  
  475. # Find a file with pattern $1 in name and Execute $2 on it:
  476. function fe() { find . -type f -iname '*'"${1:-}"'*' \
  477. -exec ${2:-file} {} \;  ; }
  478.  
  479. #  Find a pattern in a set of files and highlight them:
  480. #+ (needs a recent version of egrep).
  481. function fstr()
  482. {
  483.     OPTIND=1
  484.     local mycase=""
  485.     local usage="fstr: find string in files.
  486. Usage: fstr [-i] \"pattern\" [\"filename pattern\"] "
  487.     while getopts :it opt
  488.     do
  489.         case "$opt" in
  490.            i) mycase="-i " ;;
  491.            *) echo "$usage"; return ;;
  492.         esac
  493.     done
  494.     shift $(( $OPTIND - 1 ))
  495.     if [ "$#" -lt 1 ]; then
  496.         echo "$usage"
  497.         return;
  498.     fi
  499.     find . -type f -name "${2:-*}" -print0 | \
  500. xargs -0 egrep --color=always -sn ${case} "$1" 2>&- | more
  501.  
  502. }
  503.  
  504.  
  505. function swap()
  506. { # Swap 2 filenames around, if they exist (from Uzi's bashrc).
  507.     local TMPFILE=tmp.$$
  508.  
  509.     [ $# -ne 2 ] && echo "swap: 2 arguments needed" && return 1
  510.     [ ! -e $1 ] && echo "swap: $1 does not exist" && return 1
  511.     [ ! -e $2 ] && echo "swap: $2 does not exist" && return 1
  512.  
  513.     mv "$1" $TMPFILE
  514.     mv "$2" "$1"
  515.     mv $TMPFILE "$2"
  516. }
  517.  
  518. function extract()      # Handy Extract Program
  519. {
  520.     if [ -f $1 ] ; then
  521.         case $1 in
  522.             *.tar.bz2)   tar xvjf $1     ;;
  523.             *.tar.gz)    tar xvzf $1     ;;
  524.             *.bz2)       bunzip2 $1      ;;
  525.             *.rar)       unrar x $1      ;;
  526.             *.gz)        gunzip $1       ;;
  527.             *.tar)       tar xvf $1      ;;
  528.             *.tbz2)      tar xvjf $1     ;;
  529.             *.tgz)       tar xvzf $1     ;;
  530.             *.zip)       unzip $1        ;;
  531.             *.Z)         uncompress $1   ;;
  532.             *.7z)        7z x $1         ;;
  533.             *)           echo "'$1' cannot be extracted via >extract<" ;;
  534.         esac
  535.     else
  536.         echo "'$1' is not a valid file!"
  537.     fi
  538. }
  539.  
  540.  
  541. # Creates an archive (*.tar.gz) from given directory.
  542. function maketar() { tar cvzf "${1%%/}.tar.gz"  "${1%%/}/"; }
  543.  
  544. # Create a ZIP archive of a file or folder.
  545. function makezip() { zip -r "${1%%/}.zip" "$1" ; }
  546.  
  547. # Make your directories and files access rights sane.
  548. function sanitize() { chmod -R u=rwX,g=rX,o= "$@" ;}
  549.  
  550. #-------------------------------------------------------------
  551. # Process/system related functions:
  552. #-------------------------------------------------------------
  553.  
  554.  
  555. function my_ps() { ps $@ -u $USER -o pid,%cpu,%mem,bsdtime,command ; }
  556. function pp() { my_ps f | awk '!/awk/ && $0~var' var=${1:-".*"} ; }
  557.  
  558.  
  559. function killps()   # kill by process name
  560. {
  561.     local pid pname sig="-TERM"   # default signal
  562.     if [ "$#" -lt 1 ] || [ "$#" -gt 2 ]; then
  563.         echo "Usage: killps [-SIGNAL] pattern"
  564.         return;
  565.     fi
  566.     if [ $# = 2 ]; then sig=$1 ; fi
  567.     for pid in $(my_ps| awk '!/awk/ && $0~pat { print $1 }' pat=${!#} )
  568.     do
  569.         pname=$(my_ps | awk '$1~var { print $5 }' var=$pid )
  570.         if ask "Kill process $pid <$pname> with signal $sig?"
  571.             then kill $sig $pid
  572.         fi
  573.     done
  574. }
  575.  
  576. function mydf()         # Pretty-print of 'df' output.
  577. {                       # Inspired by 'dfc' utility.
  578.     for fs ; do
  579.  
  580.         if [ ! -d $fs ]
  581.         then
  582.           echo -e $fs" :No such file or directory" ; continue
  583.         fi
  584.  
  585.         local info=( $(command df -P $fs | awk 'END{ print $2,$3,$5 }') )
  586.         local free=( $(command df -Pkh $fs | awk 'END{ print $4 }') )
  587.         local nbstars=$(( 20 * ${info[1]} / ${info[0]} ))
  588.         local out="["
  589.         for ((j=0;j<20;j++)); do
  590.             if [ ${j} -lt ${nbstars} ]; then
  591.                out=$out"*"
  592.             else
  593.                out=$out"-"
  594.             fi
  595.         done
  596.         out=${info[2]}" "$out"] ("$free" free on "$fs")"
  597.         echo -e $out
  598.     done
  599. }
  600.  
  601.  
  602. function my_ip() # Get IP address on ethernet.
  603. {
  604.     MY_IP=$(/sbin/ifconfig eth0 | awk '/inet/ { print $2 } ' |
  605.       sed -e s/addr://)
  606.     echo ${MY_IP:-"Eth0 not connected"}
  607. }
  608.  
  609. function ii()   # Get current host related info.
  610. {
  611.     echo -e "\nYou are logged on ${BRed}$HOST"
  612.     echo -e "\n${BRed}Additionnal information:$NC " ; uname -a
  613.     echo -e "\n${BRed}Users logged on:$NC " ; w -hs |
  614.              cut -d " " -f1 | sort | uniq
  615.     echo -e "\n${BRed}Current date :$NC " ; date
  616.     echo -e "\n${BRed}Machine stats :$NC " ; uptime
  617.     echo -e "\n${BRed}Memory stats :$NC " ; free
  618.     echo -e "\n${BRed}Diskspace :$NC " ; mydf / $HOME
  619.     echo -e "\n${BRed}Local IP Address :$NC" ; my_ip
  620.     echo -e "\n${BRed}Open connections :$NC "; netstat -pan --inet;
  621.     echo
  622. }
  623.  
  624. #-------------------------------------------------------------
  625. # Misc utilities:
  626. #-------------------------------------------------------------
  627.  
  628. function repeat()       # Repeat n times command.
  629. {
  630.     local i max
  631.     max=$1; shift;
  632.     for ((i=1; i <= max ; i++)); do  # --> C-like syntax
  633.         eval "$@";
  634.     done
  635. }
  636.  
  637.  
  638. function ask()          # See 'killps' for example of use.
  639. {
  640.     echo -n "$@" '[y/n] ' ; read ans
  641.     case "$ans" in
  642.         y*|Y*) return 0 ;;
  643.         *) return 1 ;;
  644.     esac
  645. }
  646.  
  647. function corename()   # Get name of app that created a corefile.
  648. {
  649.     for file ; do
  650.         echo -n $file : ; gdb --core=$file --batch | head -1
  651.     done
  652. }
  653.  
  654.  
  655.  
  656. #=========================================================================
  657. #
  658. #  PROGRAMMABLE COMPLETION SECTION
  659. #  Most are taken from the bash 2.05 documentation and from Ian McDonald's
  660. # 'Bash completion' package (http://www.caliban.org/bash/#completion)
  661. #  You will in fact need bash more recent then 3.0 for some features.
  662. #
  663. #  Note that most linux distributions now provide many completions
  664. # 'out of the box' - however, you might need to make your own one day,
  665. #  so I kept those here as examples.
  666. #=========================================================================
  667.  
  668. if [ "${BASH_VERSION%.*}" \< "3.0" ]; then
  669.     echo "You will need to upgrade to version 3.0 for full \
  670.          programmable completion features"
  671.     return
  672. fi
  673.  
  674. shopt -s extglob        # Necessary.
  675.  
  676. complete -A hostname   rsh rcp telnet rlogin ftp ping disk
  677. complete -A export     printenv
  678. complete -A variable   export local readonly unset
  679. complete -A enabled    builtin
  680. complete -A alias      alias unalias
  681. complete -A function   function
  682. complete -A user       su mail finger
  683.  
  684. complete -A helptopic  help     # Currently same as builtins.
  685. complete -A shopt      shopt
  686. complete -A stopped -P '%' bg
  687. complete -A job -P '%'     fg jobs disown
  688.  
  689. complete -A directory  mkdir rmdir
  690. complete -A directory   -o default cd
  691.  
  692. # Compression
  693. complete -f -o default -X '*.+(zip|ZIP)'  zip
  694. complete -f -o default -X '!*.+(zip|ZIP)' unzip
  695. complete -f -o default -X '*.+(z|Z)'      compress
  696. complete -f -o default -X '!*.+(z|Z)'     uncompress
  697. complete -f -o default -X '*.+(gz|GZ)'    gzip
  698. complete -f -o default -X '!*.+(gz|GZ)'   gunzip
  699. complete -f -o default -X '*.+(bz2|BZ2)'  bzip2
  700. complete -f -o default -X '!*.+(bz2|BZ2)' bunzip2
  701. complete -f -o default -X '!*.+(zip|ZIP|z|Z|gz|GZ|bz2|BZ2)' extract
  702.  
  703.  
  704. # Documents - Postscript,pdf,dvi.....
  705. complete -f -o default -X '!*.+(ps|PS)'  gs ghostview ps2pdf ps2ascii
  706. complete -f -o default -X \
  707. '!*.+(dvi|DVI)' dvips dvipdf xdvi dviselect dvitype
  708. complete -f -o default -X '!*.+(pdf|PDF)' acroread pdf2ps
  709. complete -f -o default -X '!*.@(@(?(e)ps|?(E)PS|pdf|PDF)?\
  710. (.gz|.GZ|.bz2|.BZ2|.Z))' gv ggv
  711. complete -f -o default -X '!*.texi*' makeinfo texi2dvi texi2html texi2pdf
  712. complete -f -o default -X '!*.tex' tex latex slitex
  713. complete -f -o default -X '!*.lyx' lyx
  714. complete -f -o default -X '!*.+(htm*|HTM*)' lynx html2ps
  715. complete -f -o default -X \
  716. '!*.+(doc|DOC|xls|XLS|ppt|PPT|sx?|SX?|csv|CSV|od?|OD?|ott|OTT)' soffice
  717.  
  718. # Multimedia
  719. complete -f -o default -X \
  720. '!*.+(gif|GIF|jp*g|JP*G|bmp|BMP|xpm|XPM|png|PNG)' xv gimp ee gqview
  721. complete -f -o default -X '!*.+(mp3|MP3)' mpg123 mpg321
  722. complete -f -o default -X '!*.+(ogg|OGG)' ogg123
  723. complete -f -o default -X \
  724. '!*.@(mp[23]|MP[23]|ogg|OGG|wav|WAV|pls|\
  725. m3u|xm|mod|s[3t]m|it|mtm|ult|flac)' xmms
  726. complete -f -o default -X '!*.@(mp?(e)g|MP?(E)G|wma|avi|AVI|\
  727. asf|vob|VOB|bin|dat|vcd|ps|pes|fli|viv|rm|ram|yuv|mov|MOV|qt|\
  728. QT|wmv|mp3|MP3|ogg|OGG|ogm|OGM|mp4|MP4|wav|WAV|asx|ASX)' xine
  729.  
  730.  
  731.  
  732. complete -f -o default -X '!*.pl'  perl perl5
  733.  
  734.  
  735. #  This is a 'universal' completion function - it works when commands have
  736. #+ a so-called 'long options' mode , ie: 'ls --all' instead of 'ls -a'
  737. #  Needs the '-o' option of grep
  738. #+ (try the commented-out version if not available).
  739.  
  740. #  First, remove '=' from completion word separators
  741. #+ (this will allow completions like 'ls --color=auto' to work correctly).
  742.  
  743. COMP_WORDBREAKS=${COMP_WORDBREAKS/=/}
  744.  
  745.  
  746. _get_longopts()
  747. {
  748.   #$1 --help | sed  -e '/--/!d' -e 's/.*--\([^[:space:].,]*\).*/--\1/'| \
  749.   #grep ^"$2" |sort -u ;
  750.     $1 --help | grep -o -e "--[^[:space:].,]*" | grep -e "$2" |sort -u
  751. }
  752.  
  753. _longopts()
  754. {
  755.     local cur
  756.     cur=${COMP_WORDS[COMP_CWORD]}
  757.  
  758.     case "${cur:-*}" in
  759.        -*)      ;;
  760.         *)      return ;;
  761.     esac
  762.  
  763.     case "$1" in
  764.        \~*)     eval cmd="$1" ;;
  765.          *)     cmd="$1" ;;
  766.     esac
  767.     COMPREPLY=( $(_get_longopts ${1} ${cur} ) )
  768. }
  769. complete  -o default -F _longopts configure bash
  770. complete  -o default -F _longopts wget id info a2ps ls recode
  771.  
  772. _tar()
  773. {
  774.     local cur ext regex tar untar
  775.  
  776.     COMPREPLY=()
  777.     cur=${COMP_WORDS[COMP_CWORD]}
  778.  
  779.     # If we want an option, return the possible long options.
  780.     case "$cur" in
  781.         -*)     COMPREPLY=( $(_get_longopts $1 $cur ) ); return 0;;
  782.     esac
  783.  
  784.     if [ $COMP_CWORD -eq 1 ]; then
  785.         COMPREPLY=( $( compgen -W 'c t x u r d A' -- $cur ) )
  786.         return 0
  787.     fi
  788.  
  789.     case "${COMP_WORDS[1]}" in
  790.         ?(-)c*f)
  791.             COMPREPLY=( $( compgen -f $cur ) )
  792.             return 0
  793.             ;;
  794.         +([^Izjy])f)
  795.             ext='tar'
  796.             regex=$ext
  797.             ;;
  798.         *z*f)
  799.             ext='tar.gz'
  800.             regex='t\(ar\.\)\(gz\|Z\)'
  801.             ;;
  802.         *[Ijy]*f)
  803.             ext='t?(ar.)bz?(2)'
  804.             regex='t\(ar\.\)bz2\?'
  805.             ;;
  806.         *)
  807.             COMPREPLY=( $( compgen -f $cur ) )
  808.             return 0
  809.             ;;
  810.  
  811.     esac
  812.  
  813.     if [[ "$COMP_LINE" == tar*.$ext' '* ]]; then
  814.         # Complete on files in tar file.
  815.         #
  816.         # Get name of tar file from command line.
  817.         tar=$( echo "$COMP_LINE" | \
  818.                         sed -e 's|^.* \([^ ]*'$regex'\) .*$|\1|' )
  819.         # Devise how to untar and list it.
  820.         untar=t${COMP_WORDS[1]//[^Izjyf]/}
  821.  
  822.         COMPREPLY=( $( compgen -W "$( echo $( tar $untar $tar \
  823.                                2>/dev/null ) )" -- "$cur" ) )
  824.         return 0
  825.  
  826.     else
  827.         # File completion on relevant files.
  828.         COMPREPLY=( $( compgen -G $cur\*.$ext ) )
  829.  
  830.     fi
  831.  
  832.     return 0
  833.  
  834. }
  835.  
  836. complete -F _tar -o default tar
  837.  
  838. _make()
  839. {
  840.     local mdef makef makef_dir="." makef_inc gcmd cur prev i;
  841.     COMPREPLY=();
  842.     cur=${COMP_WORDS[COMP_CWORD]};
  843.     prev=${COMP_WORDS[COMP_CWORD-1]};
  844.     case "$prev" in
  845.         -*f)
  846.             COMPREPLY=($(compgen -f $cur ));
  847.             return 0
  848.             ;;
  849.     esac;
  850.     case "$cur" in
  851.         -*)
  852.             COMPREPLY=($(_get_longopts $1 $cur ));
  853.             return 0
  854.             ;;
  855.     esac;
  856.  
  857.     # ... make reads
  858.     #          GNUmakefile,
  859.     #     then makefile
  860.     #     then Makefile ...
  861.     if [ -f ${makef_dir}/GNUmakefile ]; then
  862.         makef=${makef_dir}/GNUmakefile
  863.     elif [ -f ${makef_dir}/makefile ]; then
  864.         makef=${makef_dir}/makefile
  865.     elif [ -f ${makef_dir}/Makefile ]; then
  866.         makef=${makef_dir}/Makefile
  867.     else
  868.        makef=${makef_dir}/*.mk         # Local convention.
  869.     fi
  870.  
  871.  
  872.     #  Before we scan for targets, see if a Makefile name was
  873.     #+ specified with -f.
  874.     for (( i=0; i < ${#COMP_WORDS[@]}; i++ )); do
  875.         if [[ ${COMP_WORDS[i]} == -f ]]; then
  876.             # eval for tilde expansion
  877.             eval makef=${COMP_WORDS[i+1]}
  878.             break
  879.         fi
  880.     done
  881.     [ ! -f $makef ] && return 0
  882.  
  883.     # Deal with included Makefiles.
  884.     makef_inc=$( grep -E '^-?include' $makef |
  885.                  sed -e "s,^.* ,"$makef_dir"/," )
  886.     for file in $makef_inc; do
  887.         [ -f $file ] && makef="$makef $file"
  888.     done
  889.  
  890.  
  891.     #  If we have a partial word to complete, restrict completions
  892.     #+ to matches of that word.
  893.     if [ -n "$cur" ]; then gcmd='grep "^$cur"' ; else gcmd=cat ; fi
  894.  
  895.     COMPREPLY=( $( awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ \
  896.                               {split($1,A,/ /);for(i in A)print A[i]}' \
  897.                                 $makef 2>/dev/null | eval $gcmd  ))
  898.  
  899. }
  900.  
  901. complete -F _make -X '+($*|*.[cho])' make gmake pmake
  902.  
  903.  
  904.  
  905.  
  906. _killall()
  907. {
  908.     local cur prev
  909.     COMPREPLY=()
  910.     cur=${COMP_WORDS[COMP_CWORD]}
  911.  
  912.     #  Get a list of processes
  913.     #+ (the first sed evaluation
  914.     #+ takes care of swapped out processes, the second
  915.     #+ takes care of getting the basename of the process).
  916.     COMPREPLY=( $( ps -u $USER -o comm  | \
  917.         sed -e '1,1d' -e 's#[]\[]##g' -e 's#^.*/##'| \
  918.         awk '{if ($0 ~ /^'$cur'/) print $0}' ))
  919.  
  920.     return 0
  921. }
  922.  
  923. complete -F _killall killall killps
  924.  
  925.  
  926.  
  927. # Local Variables:
  928. # mode:shell-script
  929. # sh-shell:bash
  930. # End:
Advertisement
Add Comment
Please, Sign In to add comment