Advertisement
Night_Wood

.bashrc

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