"Fossies" - the Fresh Open Source Software Archive

Member "abs-guide/sample-bashrc.html" (7 Mar 2014, 32158 Bytes) of package /linux/misc/abs-guide-10.html.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) HTML source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file.

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