Softpanorama
May the source be with you, but remember the KISS principle ;-)

Contents Bulletin Scripting in shell and Perl Network troubleshooting History Humor

Customizing Shell Dot Files: profile, RC-file, and history

News Shell customization Recommended Links Best Shell Books Command history reuse Examples of .bashrc files
Organizing shell aliases into knowledge database Using inputrc for key remapping Shell Prompts Customarization      
Controlling the Prompt in bash BASH Prompt Control Symbols Reference Advanced Unix filesystem navigation   AIX dotfiles .profile
Programmable Keyboards Sysadmin Horror Stories Unix shells history Tips

Humor

Etc

Introduction

Each user's common home directory contains a set of master dot files for login and run-control support. These files can be modified to customize the user environment. Dot files is probably the most important avenue of such customarization. Usage of programmable keyboard  and macros is another important avenue that is they are complementary in nature to customized dot files.

Why "." files? You probably know that ls does not show these files by default - they are somewhat hidden. Other than this, the "." files have no special significance. It is simply a Unix convention.

Creation of convenient environment for  your work is one of the criteria (and demonstration) of sysadmin abilities. Actually if a Unix sysadmin does not have his own dot files this is a warning sign as for his/her qualification.

customized dot file not only increase productivity and cut the number of keystrokes one uses during typical operations. Good prompt and carefully selected aliases and functions increases situation awareness and prevent some horrible blunders, especially if your under stress and/or in a hurry. For example such horrible mistake as rebooting the wrong server in a hurry can be prevented by redefining shutdown as a function for interactive sessions only and asking the situation "If this is a right server to reboot". Just displaying the name of the server is of great importance. Of course you should never use "now" in shutdown command anyway but mistakes are made.  

Especially acute situation arise when you find yourself working on the server or workstation that has default dot files and do not have access to your "native" dot files. In this case sites like  dotfiles.org community can be of tremendous help. See also examples in News section  below and Examples of .bashrc files

Just a couple of adjustments to .bash_profile (or .profile if ksh is used) and .bashrc (or .rc) do wonders to your mood.

This way you can turn a SNAFU into educational experience.

Key dot files

There are several fundamental files used by Unix shells such as bash or ksh93:

  1. /etc/profile -- system wide shell initialization script. Executed during login only for each user including root. .profile is a user customizable part of the profile.  Bash uses .bash_profile instead of .profile if it exists.
  2.  ~/profile, this file $HOME/.profile, also known as ~/.profile, is run exactly once per session -- when you login. As it runs after system wide /etc/profile script, the typical thing you want to do in this script is set, or modify, environment variables. If you set a shell option or alias in this script, it will not be propagated to a subshell.

  3. $ENV file (name is user selectable but usually .bashrc .kshrc,  .kshenv or .aliases). Executed upon each non-interactive invocation of the shell. If this variable contains a name of a file readable by a particular user it will be executed each time shell is invoked.

    The main difference between your $HOME/.profile and $ENV is that $ENV is run every time a shell starts, whicle $HOME/.profile runs instead when you login into interactive session. For this reason, the typical thing you want to do in this script is set, or modify

    Do not set shell options environment variables (with possible exception of $PATH) in this file.  Please note that all exported environment variables are propagated to the child processes from the login shell.

    The file should be minimal. Really minimal. Such things as aliases which are used only in interactive sessions are probably redundant and inefficient because.

Which file is executed when

Contrary to popular urban myth .logout file is not executed on logoff for ksh users. You can make it execute by defining it as an alias for exit.

See also DotFiles - Greg's Wiki

Other dot files

There are many other dot files. See In Unix, what are some common dot files.  Among them:

 

- Dr. Nikolai Bezroukov



NEWS CONTENTS

Old News ;-)

jonty /.bashrc

Commands vi and man will launch in separate screens when called inside GNU screen. You need my scr file as well.
# $HOME/.bashrc - Jonty's own settings for all shells, not just login
# Jonty 28-Aug-2005

# Shorthands to launch 'vi' or 'man' in separate screens
# when we are running in 'screen'.

function vi() { scr vi $* ; }

function man() { scr man $* ; }

cron0 /.bashrc

This one should probably be .bash_profile.
cron0 /.bashrc 

#.bashrc
export PAGER=less
export EDITOR=vim
export PATH=$HOME/bin:/usr/local/bin:/usr/local/mysql/bin:/opt/local/bin:$PATH
export LESS='-R'

if [[ $- != *i* ]] ; then
         # Shell is non-interactive.  Be done now!
         return
fi


# Fancy PWD display function
# The home directory (HOME) is replaced with a ~
# /home/me/stuff          -> ~/stuff               if USER=me
# /usr/share/big_dir_name -> ../share/big_dir_name if pwdmaxlen=20
bash_prompt_command() {
    # How many characters of the $PWD should be kept
    local pwdmaxlen=15
    # Indicate that there has been dir truncation
    local trunc_symbol=".."
    local dir=${PWD##*/}
    pwdmaxlen=$(( ( pwdmaxlen < ${#dir} ) ? ${#dir} : pwdmaxlen ))
    NEW_PWD=${PWD/#$HOME/\~}
    local pwdoffset=$(( ${#NEW_PWD} - pwdmaxlen ))
    if [ ${pwdoffset} -gt "0" ]
    then
        NEW_PWD=${NEW_PWD:$pwdoffset:$pwdmaxlen}
        NEW_PWD=${trunc_symbol}/${NEW_PWD#*/}
    fi
}

bash_prompt() {
        case $TERM in
    xterm*|rxvt*)
        local TITLEBAR='\[\033]0;\u:${NEW_PWD}\007\]'
        ;;
    *)
        local TITLEBAR=""
        ;;
        esac
        
    local NONE="\[\033[0m\]"    # unsets color to term's fg color
    
    # regular colors
    local K="\[\033[0;30m\]"    # black
    local R="\[\033[0;31m\]"    # red
    local G="\[\033[0;32m\]"    # green
    local Y="\[\033[0;33m\]"    # yellow
    local B="\[\033[0;34m\]"    # blue
    local M="\[\033[0;35m\]"    # magenta
    local C="\[\033[0;36m\]"    # cyan
    local W="\[\033[0;37m\]"    # white
    
    # empahsized (bolded) colors
    local EMK="\[\033[1;30m\]"
    local EMR="\[\033[1;31m\]"
    local EMG="\[\033[1;32m\]"
    local EMY="\[\033[1;33m\]"
    local EMB="\[\033[1;34m\]"
    local EMM="\[\033[1;35m\]"
    local EMC="\[\033[1;36m\]"
    local EMW="\[\033[1;37m\]"
    
    # background colors
    local BGK="\[\033[40m\]"
    local BGR="\[\033[41m\]"
    local BGG="\[\033[42m\]"
    local BGY="\[\033[43m\]"
    local BGB="\[\033[44m\]"
    local BGM="\[\033[45m\]"
    local BGC="\[\033[46m\]"
    local BGW="\[\033[47m\]"
    
    local UC=$W                 # user's color
    [ $UID -eq "0" ] && UC=$R   # root's color
    
    PS1="$TITLEBAR${EMK}[${UC}\u${EMK}@${UC}\h ${EMB}\${NEW_PWD}${EMK}]${UC}\\$ ${NONE}"

}
PROMPT_COMMAND=bash_prompt_command
bash_prompt
unset bash_prompt

### Bash stuff
export HISTCONTROL=ignoredups
export HISTSIZE=1000
export HISTFILESIZE=1000

### Bash options
#fix spelling
shopt -s cdspell
#makes bash append to history rather than overwrite
shopt -s histappend
#make bash check window after each command
shopt -s checkwinsize

### Misc
# disable XON/XOFF flow control (^s/^q) 
stty -ixon

# Tab complete for sudo
complete -cf sudo

#prevent overwriting files with cat
set -o noclobber

#stops ctrl+d from logging me out
#set -o ignoreeof

#Treat undefined variables as errors
set -o nounset
### Aliases
#safety! ohnoes.
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
alias mkdir='mkdir -p'
#colors
#alias ls='ls --color'
#alias ls='ls -hp --time-style=locale --color' 
alias ls='ls -G'
alias grep='grep --color=auto'
#alias ncmpc='ncmpc -c'
#unicode
#alias xterm='xterm -u8'
#alias screen='screen -U'
#sudo
#alias root='sudo su'
#alias pacman='sudo pacman'
#alias apt-get='sudo apt-get'
#alias aptitude='sudo aptitude'
#
alias cd..='cd ..'
alias more='less'
alias nano='nano -w'
alias vim='vim -X'
#alias xcomp='xcompmgr -cCfF -r7 -o.65 -l-10 -t-8 -D7'
alias servethis="python -c 'import SimpleHTTPServer; SimpleHTTPServer.test()'"
alias m='mate'
alias ss='./script/server'

###Console
#makes console terminal pretty
#slightly modified phraktured's
if [ "$TERM" = "linux" ]; then
    echo -en "\e]P0121212" #black
    echo -en "\e]P8474747" #darkgrey
    echo -en "\e]P1803232" #darkred
    echo -en "\e]P9982b2b" #red
    echo -en "\e]P25b762f" #darkgreen
    echo -en "\e]PA89b83f" #green
    echo -en "\e]P3AA9943" #dark yellow
    echo -en "\e]PBefef60" #yellow
    echo -en "\e]P4324c80" #darkblue
    echo -en "\e]PC2b4f98" #blue
    echo -en "\e]P55F5A90" #darkmagenta
    echo -en "\e]PD826ab1" #magenta
    echo -en "\e]P692b19e" #darkcyan
    echo -en "\e]PEa1cdcd" #cyan
    echo -en "\e]P7ffffff" #lightgrey
    echo -en "\e]PFdedede" #white
    clear #for background artifacting
fi


#more colors!
if [ -f ~/.dir_colors ]; then
            eval `dircolors ~/.dir_colors`
fi 
export EDITOR="/usr/bin/mate -w"

brogers /.bashrc

http://dotfiles.org/~brogers/.bashrc
complete -C ~/bin/rake_tab_completion -o default rake
complete -C ~/bin/sake_tab_completion -o default sake

export RUBYOPT=rubygems


if [ -f ~/.LifehackerTerminalTweaks ]; then
  source ~/.LifehackerTerminalTweaks
fi


An interesting example of .bashrc with the ability to extract files from archive on the base of extention (Norton COmmander functionality ;-)

http://dotfiles.org/~joephantom/.bashrc
joephantom /.bashrc 

extract () {
    if [ -f $1 ] ; then
        case $1 in
            *.tar.bz2)  tar xjf $1      ;;
            *.tar.gz)   tar xzf $1      ;;
            *.bz2)      bunzip2 $1      ;;
            *.rar)      unrar x $1      ;;
            *.gz)       gunzip $1       ;;
            *.tar)      tar xf $1       ;;
            *.tbz2)     tar xjf $1      ;;
            *.tgz)      tar xzf $1      ;;
            *.zip)      unzip $1        ;;
            *.Z)        uncompress $1   ;;
            *)          echo "'$1' cannot be extracted via extract()" ;;
        esac
    else
        echo "'$1' is not a valid file"
    fi
}
 
#
rmspaces() {
    ls | while read -r FILE
        do
        mv -v "$FILE" `echo $FILE | tr ' ' '_' | tr -d '[{}(),\!]' | tr -d "\'" | tr '[A-Z]' '[a-z]' | sed 's/_-_/_/g'`
        done
}
#
makepasswords() {
    perl <$%&()*^}));
        for (1..10) {
            print join "", map { \$a[rand @a] } (1..rand(3)+10);
            print qq{\n}
        }
EOPERL
}
 
#
alias ls='ls --color=auto'
#
#PS1="\[\e[36;1m\]\u @ \[\e[32;1m\]\H > \[\e[0m\]"
#
PS1='\[\033[0;36m\]\033(0l\033(B\[\033[0m\][\[\033[1;31m\]\u\[\033[0m\]]\[\033[0;36m\]\033(0q\033(B\[\033[0m\][\[\033[1;33m\]@\h\[\033[0m\]]\[\033[0;36m\]\033(0q\033(B\[\033[0m\][\[\033[0;37m\]\T\[\033[0m\]]\[\033[0;36m\]\033(0q\033(B\033(0q\033(B\033(0q\033(B\033(0q\033(B\033(0q\033(B\033(0q\033(B\033(0q\033(B\033(0q\033(B\[\033[0m\][\[\033[1;33m\]\w\[\033[0m\]]\n\[\033[0;36m\]\033(0m\033(B\[\033[0m\]>'
#
complete -cf sudo
alias pacs="pacsearch"
pacsearch () {
       echo -e "$(pacman -Ss $@ | sed \
       -e 's#core/.*#\\033[1;31m&\\033[0;37m#g' \
       -e 's#extra/.*#\\033[0;32m&\\033[0;37m#g' \
       -e 's#community/.*#\\033[1;35m&\\033[0;37m#g' \
       -e 's#^.*/.* [0-9].*#\\033[0;36m&\\033[0;37m#g' )"

A Sample .bashrc File

The ~/.bashrc file determines the behavior of interactive shells. A good look at this file can lead to a better understanding of Bash.

Emmanuel Rouat contributed the following very elaborate .bashrc file, written for a Linux system. He welcomes reader feedback on it.

Study the file carefully, and feel free to reuse code snippets and functions from it in your own .bashrc file or even in your scripts.

Example L-1. Sample .bashrc file
#=============================================================
#
# PERSONAL $HOME/.bashrc FILE for bash-3.0 (or later)
# By Emmanuel Rouat <no-email>
#
# Last modified: Sun Nov 30 16:27:45 CET 2008
# This file is read (normally) by interactive shells only.
# Here is the place to define your aliases, functions and
# other interactive features like your prompt.
#
# The majority of the code here assumes you are on a GNU 
# system (most likely a Linux box) and is based on code found
# on Usenet or internet. See for instance:
#
# http://tldp.org/LDP/abs/html/index.html
# http://www.caliban.org/bash/
# http://www.shelldorado.com/scripts/categories.html
# http://www.dotfiles.org/
#
# This bashrc file is a bit overcrowded -- remember it is just
# just an example. Tailor it to your needs.
#
#
#=============================================================

# --> Comments added by HOWTO author.


#-------------------------------------------------------------
# Source global definitions (if any)
#-------------------------------------------------------------


if [ -f /etc/bashrc ]; then
        . /etc/bashrc   # --> Read /etc/bashrc, if present.
fi

#-------------------------------------------------------------
# Automatic setting of $DISPLAY (if not set already).
# This works for linux - your mileage may vary. ... 
# The problem is that different types of terminals give
# different answers to 'who am i' (rxvt in particular can be
# troublesome).
# I have not found a 'universal' method yet.
#-------------------------------------------------------------

function get_xserver ()
{
    case $TERM in
       xterm )
            XSERVER=$(who am i | awk '{print $NF}' | tr -d ')''(' ) 
            # Ane-Pieter Wieringa suggests the following alternative:
            # I_AM=$(who am i)
            # SERVER=${I_AM#*(}
            # SERVER=${SERVER%*)}

            XSERVER=${XSERVER%%:*}
            ;;
        aterm | rxvt)
        # Find some code that works here. ...
            ;;
    esac  
}

if [ -z ${DISPLAY:=""} ]; then
    get_xserver
    if [[ -z ${XSERVER}  || ${XSERVER} == $(hostname) || \
      ${XSERVER} == "unix" ]]; then 
        DISPLAY=":0.0"          # Display on local host.
    else
        DISPLAY=${XSERVER}:0.0  # Display on remote host.
    fi
fi

export DISPLAY

#-------------------------------------------------------------
# Some settings
#-------------------------------------------------------------

ulimit -S -c 0          # Don't want any coredumps.
set -o notify
set -o noclobber
set -o ignoreeof
set -o nounset
#set -o xtrace          # Useful for debuging.

# Enable options:
shopt -s cdspell
shopt -s cdable_vars
shopt -s checkhash
shopt -s checkwinsize
shopt -s sourcepath
shopt -s no_empty_cmd_completion
shopt -s cmdhist
shopt -s histappend histreedit histverify
shopt -s extglob        # Necessary for programmable completion.

# Disable options:
shopt -u mailwarn
unset MAILCHECK         # Don't want my shell to warn me of incoming mail.


export TIMEFORMAT=$'\nreal %3R\tuser %3U\tsys %3S\tpcpu %P\n'
export HISTTIMEFORMAT="%H:%M > "
export HISTIGNORE="&:bg:fg:ll:h"
export HOSTFILE=$HOME/.hosts    # Put list of remote hosts in ~/.hosts ...



#-------------------------------------------------------------
# Greeting, motd etc...
#-------------------------------------------------------------

# Define some colors first:
red='\e[0;31m'
RED='\e[1;31m'
blue='\e[0;34m'
BLUE='\e[1;34m'
cyan='\e[0;36m'
CYAN='\e[1;36m'
NC='\e[0m'              # No Color
# --> Nice. Has the same effect as using "ansi.sys" in DOS.


# Looks best on a terminal with black background.....
echo -e "${CYAN}This is BASH ${RED}${BASH_VERSION%.*}\
${CYAN} - DISPLAY on ${RED}$DISPLAY${NC}\n"
date
if [ -x /usr/games/fortune ]; then
    /usr/games/fortune -s     # Makes our day a bit more fun.... :-)
fi

function _exit()        # Function to run upon exit of shell.
{
    echo -e "${RED}Hasta la vista, baby${NC}"
}
trap _exit EXIT


#-------------------------------------------------------------
# Shell Prompt
#-------------------------------------------------------------


if [[ "${DISPLAY%%:0*}" != "" ]]; then  
    HILIT=${red}   # remote machine: prompt will be partly red
else
    HILIT=${cyan}  # local machine: prompt will be partly cyan
fi

#  --> Replace instances of \W with \w in prompt functions below
#+ --> to get display of full path name.

function fastprompt()
{
    unset PROMPT_COMMAND
    case $TERM in
        *term | rxvt )
            PS1="${HILIT}[\h]$NC \W > \[\033]0;\${TERM} [\u@\h] \w\007\]" ;;
        linux )
            PS1="${HILIT}[\h]$NC \W > " ;;
        *)
            PS1="[\h] \W > " ;;
    esac
}


_powerprompt()
{
    LOAD=$(uptime|sed -e "s/.*: \([^,]*\).*/\1/" -e "s/ //g")
}

function powerprompt()
{

    PROMPT_COMMAND=_powerprompt
    case $TERM in
        *term | rxvt  )
            PS1="${HILIT}[\A - \$LOAD]$NC\n[\u@\h \#] \W > \
                 \[\033]0;\${TERM} [\u@\h] \w\007\]" ;;
        linux )
            PS1="${HILIT}[\A - \$LOAD]$NC\n[\u@\h \#] \W > " ;;
        * )
            PS1="[\A - \$LOAD]\n[\u@\h \#] \W > " ;;
    esac
}

powerprompt     # This is the default prompt -- might be slow.
                # If too slow, use fastprompt instead. ...

#===============================================================
#
# ALIASES AND FUNCTIONS
#
# Arguably, some functions defined here are quite big.
# If you want to make this file smaller, these functions can
# be converted into scripts and removed from here.
#
# Many functions were taken (almost) straight from the bash-2.04
# examples.
#
#===============================================================

#-------------------
# Personnal Aliases
#-------------------

alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
# -> Prevents accidentally clobbering files.
alias mkdir='mkdir -p'

alias h='history'
alias j='jobs -l'
alias which='type -a'
alias ..='cd ..'
alias path='echo -e ${PATH//:/\\n}'
alias libpath='echo -e ${LD_LIBRARY_PATH//:/\\n}'
alias print='/usr/bin/lp -o nobanner -d $LPDEST'
            # Assumes LPDEST is defined (default printer)
alias pjet='enscript -h -G -fCourier9 -d $LPDEST'
            # Pretty-print using enscript

alias du='du -kh'       # Makes a more readable output.
alias df='df -kTh'

#-------------------------------------------------------------
# The 'ls' family (this assumes you use a recent GNU ls)
#-------------------------------------------------------------
alias ll="ls -l --group-directories-first"
alias ls='ls -hF --color'  # add colors for filetype recognition
alias la='ls -Al'          # show hidden files
alias lx='ls -lXB'         # sort by extension
alias lk='ls -lSr'         # sort by size, biggest last
alias lc='ls -ltcr'        # sort by and show change time, most recent last
alias lu='ls -ltur'        # sort by and show access time, most recent last
alias lt='ls -ltr'         # sort by date, most recent last
alias lm='ls -al |more'    # pipe through 'more'
alias lr='ls -lR'          # recursive ls
alias tree='tree -Csu'     # nice alternative to 'recursive ls'

# If your version of 'ls' doesn't support --group-directories-first try this:
# function ll(){ ls -l "$@"| egrep "^d" ; ls -lXB "$@" 2>&-| \
#                egrep -v "^d|total "; }


#-------------------------------------------------------------
# tailoring 'less'
#-------------------------------------------------------------

alias more='less'
export PAGER=less
export LESSCHARSET='latin1'
export LESSOPEN='|/usr/bin/lesspipe.sh %s 2>&-'
   # Use this if lesspipe.sh exists
export LESS='-i -N -w  -z-4 -g -e -M -X -F -R -P%t?f%f \
:stdin .?pb%pb\%:?lbLine %lb:?bbByte %bb:-...'


#-------------------------------------------------------------
# spelling typos - highly personnal and keyboard-dependent :-)
#-------------------------------------------------------------

alias xs='cd'
alias vf='cd'
alias moer='more'
alias moew='more'
alias kk='ll'


#-------------------------------------------------------------
# A few fun ones
#-------------------------------------------------------------


function xtitle()      # Adds some text in the terminal frame.
{
    case "$TERM" in
        *term | rxvt)
            echo -n -e "\033]0;$*\007" ;;
        *)  
            ;;
    esac
}

# aliases that use xtitle
alias top='xtitle Processes on $HOST && top'
alias make='xtitle Making $(basename $PWD) ; make'
alias ncftp="xtitle ncFTP ; ncftp"

# .. and functions
function man()
{
    for i ; do
        xtitle The $(basename $1|tr -d .[:digit:]) manual
        command man -F -a "$i"
    done
}


#-------------------------------------------------------------
# Make the following commands run in background automatically:
#-------------------------------------------------------------

function te()  # Wrapper around xemacs/gnuserv ...
{
    if [ "$(gnuclient -batch -eval t 2>&-)" == "t" ]; then
        gnuclient -q "$@";
    else
        ( xemacs "$@" &);
    fi
}

function soffice() { command soffice "$@" & }
function firefox() { command firefox "$@" & }
function xpdf() { command xpdf "$@" & }


#-------------------------------------------------------------
# File & string-related functions:
#-------------------------------------------------------------


# Find a file with a pattern in name:
function ff() { find . -type f -iname '*'$*'*' -ls ; }

# Find a file with pattern $1 in name and Execute $2 on it:
function fe()
{ find . -type f -iname '*'${1:-}'*' -exec ${2:-file} {} \;  ; }

# Find a pattern in a set of files and highlight them:
# (needs a recent version of egrep)
function fstr()
{
    OPTIND=1
    local case=""
    local usage="fstr: find string in files.
Usage: fstr [-i] \"pattern\" [\"filename pattern\"] "
    while getopts :it opt
    do
        case "$opt" in
        i) case="-i " ;;
        *) echo "$usage"; return;;
        esac
    done
    shift $(( $OPTIND - 1 ))
    if [ "$#" -lt 1 ]; then
        echo "$usage"
        return;
    fi
    find . -type f -name "${2:-*}" -print0 | \
    xargs -0 egrep --color=always -sn ${case} "$1" 2>&- | more 

}

function cuttail() # cut last n lines in file, 10 by default
{
    nlines=${2:-10}
    sed -n -e :a -e "1,${nlines}!{P;N;D;};N;ba" $1
}

function lowercase()  # move filenames to lowercase
{
    for file ; do
        filename=${file##*/}
        case "$filename" in
        */*) dirname==${file%/*} ;;
        *) dirname=.;;
        esac
        nf=$(echo $filename | tr A-Z a-z)
        newname="${dirname}/${nf}"
        if [ "$nf" != "$filename" ]; then
            mv "$file" "$newname"
            echo "lowercase: $file --> $newname"
        else
            echo "lowercase: $file not changed."
        fi
    done
}


function swap()  # Swap 2 filenames around, if they exist
{                #(from Uzi's bashrc).
    local TMPFILE=tmp.$$ 

    [ $# -ne 2 ] && echo "swap: 2 arguments needed" && return 1
    [ ! -e $1 ] && echo "swap: $1 does not exist" && return 1
    [ ! -e $2 ] && echo "swap: $2 does not exist" && return 1

    mv "$1" $TMPFILE 
    mv "$2" "$1"
    mv $TMPFILE "$2"
}

function extract()      # Handy Extract Program.
{
     if [ -f $1 ] ; then
         case $1 in
             *.tar.bz2)   tar xvjf $1     ;;
             *.tar.gz)    tar xvzf $1     ;;
             *.bz2)       bunzip2 $1      ;;
             *.rar)       unrar x $1      ;;
             *.gz)        gunzip $1       ;;
             *.tar)       tar xvf $1      ;;
             *.tbz2)      tar xvjf $1     ;;
             *.tgz)       tar xvzf $1     ;;
             *.zip)       unzip $1        ;;
             *.Z)         uncompress $1   ;;
             *.7z)        7z x $1         ;;
             *)           echo "'$1' cannot be extracted via >extract<" ;;
         esac
     else
         echo "'$1' is not a valid file"
     fi
}

#-------------------------------------------------------------
# Process/system related functions:
#-------------------------------------------------------------


function my_ps() { ps $@ -u $USER -o pid,%cpu,%mem,bsdtime,command ; }
function pp() { my_ps f | awk '!/awk/ && $0~var' var=${1:-".*"} ; }


function killps()                 # Kill by process name.
{
    local pid pname sig="-TERM"   # Default signal.
    if [ "$#" -lt 1 ] || [ "$#" -gt 2 ]; then
        echo "Usage: killps [-SIGNAL] pattern"
        return;
    fi
    if [ $# = 2 ]; then sig=$1 ; fi
    for pid in $(my_ps| awk '!/awk/ && $0~pat { print $1 }' pat=${!#} ) ; do
        pname=$(my_ps | awk '$1~var { print $5 }' var=$pid )
        if ask "Kill process $pid <$pname> with signal $sig?"
            then kill $sig $pid
        fi
    done
}

function my_ip() # Get IP adresses.
{
    MY_IP=$(/sbin/ifconfig ppp0 | awk '/inet/ { print $2 } ' | \
sed -e s/addr://)
    MY_ISP=$(/sbin/ifconfig ppp0 | awk '/P-t-P/ { print $3 } ' | \
sed -e s/P-t-P://)
}

function ii()   # Get current host related info.
{
    echo -e "\nYou are logged on ${RED}$HOST"
    echo -e "\nAdditionnal information:$NC " ; uname -a
    echo -e "\n${RED}Users logged on:$NC " ; w -h
    echo -e "\n${RED}Current date :$NC " ; date
    echo -e "\n${RED}Machine stats :$NC " ; uptime
    echo -e "\n${RED}Memory stats :$NC " ; free
    my_ip 2>&- ;
    echo -e "\n${RED}Local IP Address :$NC" ; echo ${MY_IP:-"Not connected"}
    echo -e "\n${RED}ISP Address :$NC" ; echo ${MY_ISP:-"Not connected"}
    echo -e "\n${RED}Open connections :$NC "; netstat -pan --inet;
    echo
}

#-------------------------------------------------------------
# Misc utilities:
#-------------------------------------------------------------

function repeat()       # Repeat n times command.
{
    local i max
    max=$1; shift;
    for ((i=1; i <= max ; i++)); do  # --> C-like syntax
        eval "$@";
    done
}


function ask()          # See 'killps' for example of use.
{
    echo -n "$@" '[y/n] ' ; read ans
    case "$ans" in
        y*|Y*) return 0 ;;
        *) return 1 ;;
    esac
}

function corename()   # Get name of app that created a corefile.
{ 
    for file ; do
        echo -n $file : ; gdb --core=$file --batch | head -1
    done 
}




#=========================================================================
# PROGRAMMABLE COMPLETION - ONLY SINCE BASH-2.04
# Most are taken from the bash 2.05 documentation and from Ian McDonald's
# 'Bash completion' package (http://www.caliban.org/bash/#completion).
# You will in fact need bash more recent than 3.0 for some features.
#=========================================================================

if [ "${BASH_VERSION%.*}" \< "3.0" ]; then
    echo "You will need to upgrade to version 3.0 \
for full programmable completion features."
    return
fi

shopt -s extglob         # Necessary,
#set +o nounset          # otherwise some completions will fail.

complete -A hostname   rsh rcp telnet rlogin r ftp ping disk
complete -A export     printenv
complete -A variable   export local readonly unset
complete -A enabled    builtin
complete -A alias      alias unalias
complete -A function   function
complete -A user       su mail finger

complete -A helptopic  help     # Currently, same as builtins.
complete -A shopt      shopt
complete -A stopped -P '%' bg
complete -A job -P '%'     fg jobs disown

complete -A directory  mkdir rmdir
complete -A directory   -o default cd

# Compression
complete -f -o default -X '*.+(zip|ZIP)'  zip
complete -f -o default -X '!*.+(zip|ZIP)' unzip
complete -f -o default -X '*.+(z|Z)'      compress
complete -f -o default -X '!*.+(z|Z)'     uncompress
complete -f -o default -X '*.+(gz|GZ)'    gzip
complete -f -o default -X '!*.+(gz|GZ)'   gunzip
complete -f -o default -X '*.+(bz2|BZ2)'  bzip2
complete -f -o default -X '!*.+(bz2|BZ2)' bunzip2
complete -f -o default -X '!*.+(zip|ZIP|z|Z|gz|GZ|bz2|BZ2)' extract


# Documents - Postscript,pdf,dvi.....
complete -f -o default -X '!*.+(ps|PS)'  gs ghostview ps2pdf ps2ascii
complete -f -o default -X '!*.+(dvi|DVI)' dvips dvipdf xdvi dviselect dvitype
complete -f -o default -X '!*.+(pdf|PDF)' acroread pdf2ps
complete -f -o default -X \
'!*.@(@(?(e)ps|?(E)PS|pdf|PDF)?(.gz|.GZ|.bz2|.BZ2|.Z))' gv ggv
complete -f -o default -X '!*.texi*' makeinfo texi2dvi texi2html texi2pdf
complete -f -o default -X '!*.tex' tex latex slitex
complete -f -o default -X '!*.lyx' lyx
complete -f -o default -X '!*.+(htm*|HTM*)' lynx html2ps
complete -f -o default -X \
'!*.+(doc|DOC|xls|XLS|ppt|PPT|sx?|SX?|csv|CSV|od?|OD?|ott|OTT)' soffice

# Multimedia
complete -f -o default -X \
'!*.+(gif|GIF|jp*g|JP*G|bmp|BMP|xpm|XPM|png|PNG)' xv gimp ee gqview
complete -f -o default -X '!*.+(mp3|MP3)' mpg123 mpg321
complete -f -o default -X '!*.+(ogg|OGG)' ogg123
complete -f -o default -X \
'!*.@(mp[23]|MP[23]|ogg|OGG|wav|WAV|pls|m3u|xm|mod|s[3t]m|it|mtm|ult|flac)' xmms
complete -f -o default -X \
'!*.@(mp?(e)g|MP?(E)G|wma|avi|AVI|asf|vob|VOB|bin|dat|vcd|\
ps|pes|fli|viv|rm|ram|yuv|mov|MOV|qt|QT|wmv|mp3|MP3|ogg|OGG|\
ogm|OGM|mp4|MP4|wav|WAV|asx|ASX)' xine



complete -f -o default -X '!*.pl'  perl perl5


# This is a 'universal' completion function - it works when commands have
# a so-called 'long options' mode , ie: 'ls --all' instead of 'ls -a'
# Needs the '-o' option of grep
#  (try the commented-out version if not available).

# First, remove '=' from completion word separators
# (this will allow completions like 'ls --color=auto' to work correctly).

COMP_WORDBREAKS=${COMP_WORDBREAKS/=/}


_get_longopts() 
{ 
    #$1 --help | sed  -e '/--/!d' -e 's/.*--\([^[:space:].,]*\).*/--\1/'| \
#grep ^"$2" |sort -u ;
    $1 --help | grep -o -e "--[^[:space:].,]*" | grep -e "$2" |sort -u 
}

_longopts()
{
    local cur
    cur=${COMP_WORDS[COMP_CWORD]}

    case "${cur:-*}" in
       -*)      ;;
        *)      return ;;
    esac

    case "$1" in
      \~*)      eval cmd="$1" ;;
        *)      cmd="$1" ;;
    esac
    COMPREPLY=( $(_get_longopts ${1} ${cur} ) )
}
complete  -o default -F _longopts configure bash
complete  -o default -F _longopts wget id info a2ps ls recode

_tar()
{
    local cur ext regex tar untar

    COMPREPLY=()
    cur=${COMP_WORDS[COMP_CWORD]}

    # If we want an option, return the possible long options.
    case "$cur" in
        -*)     COMPREPLY=( $(_get_longopts $1 $cur ) ); return 0;;
    esac

    if [ $COMP_CWORD -eq 1 ]; then
        COMPREPLY=( $( compgen -W 'c t x u r d A' -- $cur ) )
        return 0
    fi

    case "${COMP_WORDS[1]}" in
        ?(-)c*f)
            COMPREPLY=( $( compgen -f $cur ) )
            return 0
            ;;
            +([^Izjy])f)
            ext='tar'
            regex=$ext
            ;;
        *z*f)
            ext='tar.gz'
            regex='t\(ar\.\)\(gz\|Z\)'
            ;;
        *[Ijy]*f)
            ext='t?(ar.)bz?(2)'
            regex='t\(ar\.\)bz2\?'
            ;;
        *)
            COMPREPLY=( $( compgen -f $cur ) )
            return 0
            ;;

    esac

    if [[ "$COMP_LINE" == tar*.$ext' '* ]]; then
        # Complete on files in tar file.
        #
        # Get name of tar file from command line.
        tar=$( echo "$COMP_LINE" | \
               sed -e 's|^.* \([^ ]*'$regex'\) .*$|\1|' )
        # Devise how to untar and list it.
        untar=t${COMP_WORDS[1]//[^Izjyf]/}

        COMPREPLY=( $( compgen -W "$( echo $( tar $untar $tar \
                    2>/dev/null ) )" -- "$cur" ) )
        return 0

    else
        # File completion on relevant files.
        COMPREPLY=( $( compgen -G $cur\*.$ext ) )

    fi

    return 0

}

complete -F _tar -o default tar

_make()
{
    local mdef makef makef_dir="." makef_inc gcmd cur prev i;
    COMPREPLY=();
    cur=${COMP_WORDS[COMP_CWORD]};
    prev=${COMP_WORDS[COMP_CWORD-1]};
    case "$prev" in
        -*f)
            COMPREPLY=($(compgen -f $cur ));
            return 0
        ;;
    esac;
    case "$cur" in
        -*)
            COMPREPLY=($(_get_longopts $1 $cur ));
            return 0
        ;;
    esac;

    # make reads `GNUmakefile', then `makefile', then `Makefile'
    if [ -f ${makef_dir}/GNUmakefile ]; then
        makef=${makef_dir}/GNUmakefile
    elif [ -f ${makef_dir}/makefile ]; then
        makef=${makef_dir}/makefile
    elif [ -f ${makef_dir}/Makefile ]; then
        makef=${makef_dir}/Makefile
    else
        makef=${makef_dir}/*.mk        # Local convention.
    fi


    # Before we scan for targets, see if a Makefile name was
    # specified with -f ...
    for (( i=0; i < ${#COMP_WORDS[@]}; i++ )); do
        if [[ ${COMP_WORDS[i]} == -f ]]; then
           # eval for tilde expansion
           eval makef=${COMP_WORDS[i+1]}
           break
        fi
    done
    [ ! -f $makef ] && return 0

    # deal with included Makefiles
    makef_inc=$( grep -E '^-?include' $makef | \
    sed -e "s,^.* ,"$makef_dir"/," )
    for file in $makef_inc; do
        [ -f $file ] && makef="$makef $file"
    done


    # If we have a partial word to complete, restrict completions to
    # matches of that word.
    if [ -n "$cur" ]; then gcmd='grep "^$cur"' ; else gcmd=cat ; fi

    COMPREPLY=( $( awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ \
                                {split($1,A,/ /);for(i in A)print A[i]}' \
                                $makef 2>/dev/null | eval $gcmd  ))

}

complete -F _make -X '+($*|*.[cho])' make gmake pmake




_killall()
{
    local cur prev
    COMPREPLY=()
    cur=${COMP_WORDS[COMP_CWORD]}

    # get a list of processes (the first sed evaluation
    # takes care of swapped out processes, the second
    # takes care of getting the basename of the process)
    COMPREPLY=( $( /usr/bin/ps -u $USER -o comm  | \
        sed -e '1,1d' -e 's#[]\[]##g' -e 's#^.*/##'| \
        awk '{if ($0 ~ /^'$cur'/) print $0}' ))

    return 0
}

complete -F _killall killall killps



# A meta-command completion function for commands like sudo(8), which need to
# first complete on a command, then complete according to that command's own
# completion definition - currently not quite foolproof,
# but still quite useful (By Ian McDonald, modified by me).


_meta_comp()
{
    local cur func cline cspec

    COMPREPLY=()
    cur=${COMP_WORDS[COMP_CWORD]}
    cmdline=${COMP_WORDS[@]}
    if [ $COMP_CWORD = 1 ]; then  
         COMPREPLY=( $( compgen -c $cur ) )
    else
        cmd=${COMP_WORDS[1]}            # Find command.
        cspec=$( complete -p ${cmd} )   # Find spec of that command.

        # COMP_CWORD and COMP_WORDS() are not read-only,
        # so we can set them before handing off to regular
        # completion routine:
        # Get current command line minus initial command,
        cline="${COMP_LINE#$1 }"
        # split current command line tokens into array,
        COMP_WORDS=( $cline )
        # set current token number to 1 less than now.
        COMP_CWORD=$(( $COMP_CWORD - 1 ))
        # If current arg is empty, add it to COMP_WORDS array
        # (otherwise that information will be lost).
        if [ -z $cur ]; then COMP_WORDS[COMP_CWORD]=""  ; fi

        if [ "${cspec%%-F *}" != "${cspec}" ]; then
      # if -F then get function:
            func=${cspec#*-F }
            func=${func%% *}
            eval $func $cline   # Evaluate it.
        else
            func=$( echo $cspec | sed -e 's/^complete//' -e 's/[^ ]*$//' )
            COMPREPLY=( $( eval compgen $func $cur ) )
        fi

    fi
    
}


complete -o default -F _meta_comp nohup \
eval exec trace truss strace sotruss gdb
complete -o default -F _meta_comp command type which man nice time

# Local Variables:
# mode:shell-script
# sh-shell:bash
# End:

Bash Shell PS1: 10 Examples to Make Your Linux Prompt like Angelina Jolie

3. Display output of any Linux command in the prompt

You can display output of any Linux command in the prompt. The following example displays three items separated by | (pipe) in the command prompt:

ramesh@dev-db ~> kernel_version=$(uname -r)
ramesh@dev-db ~> export PS1="\!|\h|$kernel_version|\$?> "
473|dev-db|2.6.25-14.fc9.i686|0>

4. Change foreground color of the prompt

Display prompt in blue color, along with username, host and current directory information

$ export PS1="\e[0;34m\u@\h \w> \e[m"
[Note: This is for light blue prompt]

$ export PS1="\e[1;34m\u@\h \w> \e[m"
[Note: This is for dark blue prompt]

Color Code Table:

Black 0;30
Blue 0;34
Green 0;32
Cyan 0;36
Red 0;31
Purple 0;35
Brown 0;33
[Note: Replace 0 with 1 for dark color]

Make the color change permanent by adding the following lines to .bash_profile or .bashrc

STARTCOLOR='\e[0;34m';
ENDCOLOR="\e[0m"
export PS1="$STARTCOLOR\u@\h \w> $ENDCOLOR"

5. Change background color of the prompt

Change the background color by specifying \e[{code}m in the PS1 prompt as shown below.

$ export PS1="\e[47m\u@\h \w> \e[m"
[Note: This is for Light Gray background]

Combination of background and foreground

export PS1="\e[0;34m\e[47m\u@\h \w> \e[m"
[Note: This is for Light Blue foreground and Light Gray background]

Add the following to the .bash_profile or .bashrc to make the above background and foreground color permanent.

STARTFGCOLOR='\e[0;34m';
STARTBGCOLOR="\e[47m"
ENDCOLOR="\e[0m"
export PS1="$STARTFGCOLOR$STARTBGCOLOR\u@\h \w> $ENDCOLOR"

Play around by using the following background color and choose the one that suites your taste:

6. Display multiple colors in the prompt

You can also display multiple colors in the same prompt. Add the following function to .bash_profile

function prompt {
  local BLUE="\[\033[0;34m\]"
  local DARK_BLUE="\[\033[1;34m\]"
  local RED="\[\033[0;31m\]"
  local DARK_RED="\[\033[1;31m\]"
  local NO_COLOR="\[\033[0m\]"
  case $TERM in
    xterm*|rxvt*)
      TITLEBAR=’\[\033]0;\u@\h:\w\007\]’
      ;;
    *)
      TITLEBAR=""
      ;;
  esac
  PS1="\u@\h [\t]> "
  PS1="${TITLEBAR}\
  $BLUE\u@\h $RED[\t]>$NO_COLOR "
  PS2=’continue-> ‘
  PS4=’$0.$LINENO+ ‘
}

You can re-login for the changes to take effect or source the .bash_profile as shown below.

$. ./.bash_profile
$ prompt
ramesh@dev-db [13:02:13]>

7. Change the prompt color using tput

You can also change color of the PS1 prompt using tput as shown below:

$ export PS1="\[$(tput bold)$(tput setb 4)$(tput setaf 7)\]\u@\h:\w $ \[$(tput sgr0)\]“

tput Color Capabilities:

tput Text Mode Capabilities:

Color Code for tput:

[Dec 9, 2007] Cool Solutions Bash - Making use of your .bashrc file

Too big but some ideas probably can be borrowed...

Details

I was playing with my .bashrc file again, and was once again impressed by how you can tweak Linux to do what YOU want it to do so easily. I am sure there are tons of other tweaks you can do to your .bashrc file, but I really like some of mine, and thought I would share them. Some of the alias's I created, some I found on the net, and some things in my .bashrc file are just there for fun, like the "# WELCOME SCREEN", although it does serve a purpose for me at the same time, it might not be something everyone would want or need.

For those that don't know what a .bashrc file does: "The ~/.bashrc file determines the behavior of interactive shells." Quoted From: The Advanced Bash Scripting Guide 

Basically , it allows you to create shortcuts (alias's) and interactive programs (functions) that run on the startup of the bash shell or that are used when running an interactive shell. For example, it's much easier to just type: ebrc instead of pico ~/.bashrc (I used the alias ebrc , and it stands for "Edit Bash RC file". I could have also aliased it to just use one letter, making it a VERY fast short cut. The bashrc file allows you to create alias's (shortcuts) to almost anything you want. My list is pretty long, but I'm sure there is someone with a longer list ;)

I have my .bashrc file setup in sections. The following is the breakdown by section of how I keep my list of alias's and functions separated. This is just how I do this, your .bashrc file can be modified to suit YOUR needs, that's the interesting part about the .bashrc file. It's VERY customizable and very easy to change.

Header (So I know when i modified it last and what i was running it on)
Exports (So I can set history size, paths , editors, define colors, etc,)
Sourced Alias's (So I can find those hidden alias's faster)
Workstation Alias's (so i can ssh to local machines quickly)
Remote Server Alias's (so i can ssh to remote servers easily)
Script Alias's (quick links to some of my bashscripts)
Hardware control alias's (so I can control cd/dvd/scanners/audio/etc)
Modified commands (Alias's to normal linux commands with special flags)
Chmod Alias's (makes changing permissions faster)
Alias's for GUI programs (start firefox, etc from command line)
Alias's for xterm and others (open xterm with special settings)
Alias's for Lynx (open lynx with urls - kind of a bash bookmark ;) )
UNused Alias's (Alias's that aren't in use on the system, but that i might use later)
Special functions (more of a function than just an alias..it goes here)
Notes (that should be self explanatory ;) )
Welcome Screen (code to make my bash shell display some stuff as it starts up)

That's how I lay out my .bashrc files. It may not be perfect, but it works well for me. I like making changes in just my .bashrc file and not the global files. I like the .bashrc file because you don't need root permissions to make changes that make your life easier at the bash shell.

The following is my .bashrc file (with some things obviously commented out for security... but most of it should be self explanatory). Anyone with comments/suggestions/ideas feel free to let me know. I'm always looking for new and interesting things to do with the .bashrc file.

Want to know what alias's your bash shell has? Simply type the word alias at the command line. The shell will then print out the list of active alias's to the standard output (normally your screen).

#######################################################
# Dave Crouse's .bashrc file
# www.bashscripts.org
# www.usalug.org
#
# Last Modified 04-08-2006
# Running on OpenSUSE 10
#######################################################


# EXPORTS
#######################################################

PATH=$PATH:/usr/lib/festival/ ;export PATH
export PS1="[\[\033[1;34m\w\[\033[0m]\n[\t \u]$ "
export EDITOR=/usr/bin/pico
export HISTFILESIZE=3000 # the bash history should save 3000 commands
export HISTCONTROL=ignoredups #don't put duplicate lines in the history.
alias hist='history | grep $1' #Requires one input

# Define a few Color's
BLACK='\e[0;30m'
BLUE='\e[0;34m'
GREEN='\e[0;32m'
CYAN='\e[0;36m'
RED='\e[0;31m'
PURPLE='\e[0;35m'
BROWN='\e[0;33m'
LIGHTGRAY='\e[0;37m'
DARKGRAY='\e[1;30m'
LIGHTBLUE='\e[1;34m'
LIGHTGREEN='\e[1;32m'
LIGHTCYAN='\e[1;36m'
LIGHTRED='\e[1;31m'
LIGHTPURPLE='\e[1;35m'
YELLOW='\e[1;33m'
WHITE='\e[1;37m'
NC='\e[0m'              # No Color
# Sample Command using color: echo -e "${CYAN}This is BASH
${RED}${BASH_VERSION%.*}${CYAN} - DISPLAY on ${RED}$DISPLAY${NC}\n"


# SOURCED ALIAS'S AND SCRIPTS
#######################################################

### Begin insertion of bbips alias's ###
source ~/.bbips/commandline/bbipsbashrc
### END bbips alias's ###

# Source global definitions
if [ -f /etc/bashrc ]; then
    . /etc/bashrc
fi

# enable programmable completion features
if [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
fi


# ALIAS'S OF ALL TYPES SHAPES AND FORMS ;)
#######################################################

# Alias's to local workstations
alias tom='ssh 192.168.2.102 -l root'
alias jason='ssh 192.168.2.103 -l root'
alias randy='ssh 192.168.2.104 -l root'
alias bob='ssh 192.168.2.105 -l root'
alias don='ssh 192.168.2.106 -l root'
alias counter='ssh 192.168.2.107 -l root'

# ALIAS TO REMOTE SERVERS
alias ANYNAMEHERE='ssh YOURWEBSITE.com -l USERNAME -p PORTNUMBERHERE'
# My server info removed from above for obvious reasons ;)

# Alias's to TN5250 programs. AS400 access commands.
alias d1='xt5250 env.TERM = IBM-3477-FC env.DEVNAME=D1 192.168.2.5 &'
alias d2='xt5250 env.TERM = IBM-3477-FC env.DEVNAME=D2 192.168.2.5 &'
alias tn5250j='nohup java -jar /home/crouse/tn5250j/lib/tn5250j.jar
2>>error.log &'

# Alias's to some of my BashScripts
alias bics='sh /home/crouse/scripts/bics/bics.sh'
alias backup='sh /home/crouse/scripts/usalugbackup.sh'
alias calc='sh /home/crouse/scripts/bashcalc.sh'
alias makepdf='sh /home/crouse/scripts/makepdf.sh'
alias phonebook='sh /home/crouse/scripts/PHONEBOOK/baps.sh'
alias pb='sh /home/crouse/scripts/PHONEBOOK/baps.sh'
alias ppe='/home/crouse/scripts/passphraseencryption.sh'
alias scripts='cd /home/crouse/scripts'

# Alias's to control hardware
alias cdo='eject /dev/cdrecorder'
alias cdc='eject -t /dev/cdrecorder'
alias dvdo='eject /dev/dvd'
alias dvdc='eject -t /dev/dvd'
alias scan='scanimage -L'
alias playw='for i in *.wav; do play $i; done'
alias playo='for i in *.ogg; do play $i; done'
alias playm='for i in *.mp3; do play $i; done'
alias copydisk='dd if=/dev/dvd of=/dev/cdrecorder' # Copies bit by bit
from dvd to cdrecorder drives.
alias dvdrip='vobcopy -i /dev/dvd/ -o ~/DVDs/ -l'

# Alias's to modified commands
alias ps='ps auxf'
alias home='cd ~'
alias pg='ps aux | grep'  #requires an argument
alias un='tar -zxvf'
alias mountedinfo='df -hT'
alias ping='ping -c 10'
alias openports='netstat -nape --inet'
alias ns='netstat -alnp --protocol=inet | grep -v CLOSE_WAIT | cut
-c-6,21-94 | tail +2'
alias du1='du -h --max-depth=1'
alias da='date "+%Y-%m-%d %A    %T %Z"'
alias ebrc='pico ~/.bashrc'

# Alias to multiple ls commands
alias la='ls -Al'               # show hidden files
alias ls='ls -aF --color=always' # add colors and file type extensions
alias lx='ls -lXB'              # sort by extension
alias lk='ls -lSr'              # sort by size
alias lc='ls -lcr'      # sort by change time
alias lu='ls -lur'      # sort by access time
alias lr='ls -lR'               # recursive ls
alias lt='ls -ltr'              # sort by date
alias lm='ls -al |more'         # pipe through 'more'

# Alias chmod commands
alias mx='chmod a+x'
alias 000='chmod 000'
alias 644='chmod 644'
alias 755='chmod 755'

# Alias Shortcuts to graphical programs.
alias kwrite='kwrite 2>/dev/null &'
alias firefox='firefox 2>/dev/null &'
alias gaim='gaim 2>/dev/null &'
alias kate='kate 2>/dev/null &'
alias suk='kdesu konqueror 2>/dev/null &'

# Alias xterm and aterm
alias term='xterm -bg AntiqueWhite -fg Black &'
alias termb='xterm -bg AntiqueWhite -fg NavyBlue &'
alias termg='xterm -bg AntiqueWhite -fg OliveDrab &'
alias termr='xterm -bg AntiqueWhite -fg DarkRed &'
alias aterm='aterm -ls -fg gray -bg black'
alias xtop='xterm -fn 6x13 -bg LightSlateGray -fg black -e top &'
alias xsu='xterm -fn 7x14 -bg DarkOrange4 -fg white -e su &'

# Alias for lynx web browser
alias bbc='lynx -term=vt100 http://news.bbc.co.uk/text_only.stm'
alias nytimes='lynx -term=vt100 http://nytimes.com'
alias dmregister='lynx -term=vt100 http://desmoinesregister.com'


# SOME OF MY UNUSED ALIAS's
#######################################################

# alias d=`echo "Good Morning Dave. today's date is" | festival --tts;
date +'%A %B %e' | festival --tts`
# alias shrink84='/home/crouse/shrink84/shrink84.sh'
# alias tl='tail -f /var/log/apache/access.log'
# alias te='tail -f /var/log/apache/error.log'


# SPECIAL FUNCTIONS
#######################################################

netinfo ()
{
echo "--------------- Network Information ---------------"
/sbin/ifconfig | awk /'inet addr/ {print $2}'
echo ""
/sbin/ifconfig | awk /'Bcast/ {print $3}'
echo ""
/sbin/ifconfig | awk /'inet addr/ {print $4}'

# /sbin/ifconfig | awk /'HWaddr/ {print $4,$5}'
echo "---------------------------------------------------"
}

spin ()
{
echo -ne "${RED}-"
echo -ne "${WHITE}\b|"
echo -ne "${BLUE}\bx"
sleep .02
echo -ne "${RED}\b+${NC}"
}

scpsend ()
{
scp -P PORTNUMBERHERE "$@"
USERNAME@YOURWEBSITE.com:/var/www/html/pathtodirectoryonremoteserver/;
}


# NOTES
#######################################################

# To temporarily bypass an alias, we preceed the command with a \
# EG:  the ls command is aliased, but to use the normal ls command you would
# type \ls

# mount -o loop /home/crouse/NAMEOFISO.iso /home/crouse/ISOMOUNTDIR/
# umount /home/crouse/NAMEOFISO.iso
# Both commands done as root only.


# WELCOME SCREEN
#######################################################

clear
for i in `seq 1 15` ; do spin; done ;echo -ne "${WHITE} USA Linux Users
Group ${NC}"; for i in `seq 1 15` ; do spin; done ;echo "";
echo -e ${LIGHTBLUE}`cat /etc/SUSE-release` ;
echo -e "Kernel Information: " `uname -smr`;
echo -e ${LIGHTBLUE}`bash --version`;echo ""
echo -ne "Hello $USER today is "; date
echo -e "${WHITE}"; cal ; echo "";
echo -ne "${CYAN}";netinfo;
mountedinfo ; echo ""
echo -ne "${LIGHTBLUE}Uptime for this computer is ";uptime | awk /'up/
{print $3,$4}'
for i in `seq 1 15` ; do spin; done ;echo -ne "${WHITE} http://usalug.org
${NC}"; for i in `seq 1 15` ; do spin; done ;echo "";
echo ""; echo ""The following belong under the "function" section in my .bashrc. Useable as seperate programs, I've integrated them simply as functions for my .bashrc file in order to make them quick to use and easy to modify and find. These are functions that are used to symetrically encrypt and to decrypt files and messages. Some are completely command line, and the last two create gui interfaces to locate the files to encrypt/decrypt. If you create a program out of the functions creating a link via a shortcut/icon on the desktop would create a completely gui based interface to locate and encrypt/decrypt files. Either way, it's an easy way to use gpg.

Requires: zenity, gpg

################### Begin gpg functions ##################
encrypt ()
{
# Use ascii armor
gpg -ac --no-options "$1"
}

bencrypt ()
{
# No ascii armor
# Encrypt binary data. jpegs/gifs/vobs/etc.
gpg -c --no-options "$1"
}

decrypt ()
{
gpg --no-options "$1"
}

pe ()
{
# Passphrase encryption program
# Created by Dave Crouse 01-13-2006
# Reads input from text editor and encrypts to screen.
clear
echo "         Passphrase Encryption Program";
echo "--------------------------------------------------"; echo "";
which $EDITOR &>/dev/null
 if [ $? != "0" ];
     then
     echo "It appears that you do not have a text editor set in your
.bashrc file.";
     echo "What editor would you like to use ? " ;
     read EDITOR ; echo "";
 fi
echo "Enter the name/comment for this message :"
read comment
$EDITOR passphraseencryption
gpg --armor --comment "$comment" --no-options --output
passphraseencryption.gpg --symmetric passphraseencryption
shred -u passphraseencryption ; clear
echo "Outputting passphrase encrypted message"; echo "" ; echo "" ;
cat passphraseencryption.gpg ; echo "" ; echo "" ;
shred -u passphraseencryption.gpg ;
read -p "Hit enter to exit" temp; clear
}

keys ()
{
# Opens up kgpg keymanager
kgpg -k
}

encryptfile ()
{
zenity --title="zcrypt: Select a file to encrypt" --file-selection > zcrypt
encryptthisfile=`cat zcrypt`;rm zcrypt
# Use ascii armor
#  --no-options (for NO gui usage)
gpg -acq --yes ${encryptthisfile}
zenity --info --title "File Encrypted" --text "$encryptthisfile has been
encrypted"
}

decryptfile ()
{
zenity --title="zcrypt: Select a file to decrypt" --file-selection > zcrypt
decryptthisfile=`cat zcrypt`;rm zcrypt
# NOTE: This will OVERWRITE existing files with the same name !!!
gpg --yes -q ${decryptthisfile}
zenity --info --title "File Decrypted" --text "$encryptthisfile has been
decrypted"
}

################### End gpg functions ##################

[Jun 11, 2007] Life After Coffee » Customize your bash prompt

  1. I stumbled upon this site and thought I could give Gary’s promt a try. I like it a lot and modified it a bit for use with colorful terminals. Here’s what I use now:


    PS1="\[33[01;32m\]\u@\h \[33[01;31m\]uid:\${UID} \[33[01;34m\]\d \[33[01;33m\]\w
    \[33[00m\]\t \[33[01;32m\]>\[33[00m\] "

    The uid display is arguable I guess and I use it only on the root prompt.

    Cheers !

[Dec 22, 2006] Robert Body - escape codes for ksh in -etc-profile ... was Re mkpasswd, mkgroup - ini

22 Nov 2005 (cygwin.com) First, let me say... Cygwin is awesome, and the mailing lists are awesome.
It looks like a lot of work has been done to make it match a real unix.
:-)
**************************

Brian, another great help, thank you, especially for thelink:
--- http://cygwin.com/faq/faq.setup.html#faq.setup.home
HOME is determined as follows in order of decreasing priority:
1. HOME from the Windows environment, translated to POSIX form.
2. The entry in /etc/passwd
3. HOMEDRIVE and HOMEPATH from the Windows environment
4. /
---------
so, %HOME% variable set in Windows takes priority over  /etc/passwd
That has puzzled me for a few days because all the unix people say
"yup, change the user entry in /etc/passwd and that's your new home"

#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#
Actually, yes I can make my own group in cygwin :-)
(just needs a little unix stuff)
i called it "local" and set the group number of 10546 arbitrarily (a number not already used... and this is regular unix way of doing it)
--------------------
cat /etc/group
...
local:S-1-5-32-545:10546:robert.body
--------------------


and then in /etc/passwd, the 4th field I set to my newly created "local" group
--------------------
cat /etc/group
...
robert.body:unused_by_nt/2000/xp:13550:10546:
robert.body,U-DEN\robert.body,S-1-5-21-1659004503-484061587-839522115-3550:
/cygdrive/c/home/Owner:/bin/bash
--------------------

and then ... ta-daaaa ... my own group of "local"

/cygdrive/c/cygwin/home/Owner> touch 1; ls -alp 1
-rw-r--r--  1 robert.body local 0 Nov 22 12:17 1
/cygdrive/c/cygwin/home/Owner>
#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--#--

I don't suppose there is a way of NOT letting %HOME% take priority over "/etc/passwd" for my home directory?

Brian,since you know about so many things, how come the following ksh doesn't work in
1) Linux xyz 2.4.7-10 #1 Thu Sep 6 17:27:27 EDT 2001 i686 unknown
2) HP-UX xyz B.11.00 U 9000/785 2004606272 unlimited-user license

the PS1 line below puts path into the title of the xterm, and puts "$PWD" into prompt
and this works fine in bash (different section of /etc/profile), but not in ksh

---------taken from cygwin's /etc/profile--------------------
...
ksh*     | -ksh*     | */ksh* | \
ksh*.exe | -ksh*.exe | */ksh*.exe )
       # Set a HOSTNAME variable
       typeset -l HOSTNAME

# Set a default prompt of: user@host and current_directory
PS1='^[]0;${PWD}^G
^[[32m${USER}@${HOSTNAME} ^[[33m${PWD}^[[0m
$ '
-------------------------------------------------------------
Basically the escape codes are being ignored in ksh, but it came from cygwin's /etc/profile so it must be perfect right?
(i set USER=me and HOSTNAME=myserver
(I execute t2, copied cygwin file with the above):

1) cygwin-----------------running pdksh from today's setup.exe-------
$echo $0
ksh
$. /etc/profile
^[]0;/cygdrive/u^G
^[[32mrobert.body@dpc6528 ^[[33m/cygdrive/u^[[0m
$

2) linux-----------------------------------
$. t2
^[]0;/tmp^G
^[[32mme@myserver ^[[33m/tmp^[[0m
$

3) hp-----------------------------------
$. t2
^[]0;/OnSight/opscntl^G
^[[32mme@myserver ^[[33m/OnSight/opscntl^[[0m
$
-----------------------------------------

-Robert

[Dec 22, 2006]UNIX projects

The PS1 prompt

If you want to have the prompt above with user@nameserver:directory I can recommend these settings for Korn shell

UID=`id -u`
case $UID in
0) PS1S='# ';;
esac
PS1S=${PS1S:-'$ '}
HOSTNAME=${HOSTNAME:-`uname -n`}
HOST=${HOSTNAME%%.*}
# Set prompt
PS1='$USER@$HOST:${PWD##*/}$PS1S'
 
This will make your root prompt be a # and other users have $, while having the hostname without the domain name and only the last part of the working directory is shown.

[Dec 22, 2006] Learn Unix - A sample .profile for Korn shell users

#-----------------------------------------------#
# A sample .profile file for Korn shell users #
#-----------------------------------------------#
# Courtesy of Developer's Daily #
# http://www.DevDaily.com #
#-----------------------------------------------#

PATH=$PATH:/usr/local/bin:/usr/gnu/bin:.

set -o vi # enable the ability to recall previous commands with

PS1='$PWD> ' # set the prompt to display the current directory

#----------------------------#
# a few Korn shell aliases #
#----------------------------#

alias lc="ls -C"
alias lm="ls -al | more"
alias dirs="ls -al | grep '^d'" # show the dir's in the current dir
alias h=history # show the history of commands issued

alias nu="who|wc -l" # nu - number of users
alias np="ps -ef|wc -l" # np - number of processes running
alias p="ps -ef"

# mimick a few DOS commands with these aliases:

alias cd..="cd ../.."
alias cd...="cd ../../.."
alias dir="ls -al"
alias edit=vi
alias help=man
alias path="echo $PATH"

[Dec 20, 2006] The UNIX Forums - Edit .profile

RTM 06-11-2002, 11:32 AM

Here is a good example from ksh .profile for Solaris

################################################################################
# Name: .profile
# Description: This is root's profile. Login shells source this after
# /etc/profile. It is used to define root's environment.
# All non-environment configuration will be done in the
# shell specific resource file.
# Special: ENV= is specific to ksh to indicate the name of it's
# resource file. Bourne shell ignores this.
# Author: Ryan T. Tennant
# Version: 0.1
# Date: 2000/08/09
#
################################################################################

default_paths() {
PATH="/usr/bin:/usr/sbin:/sbin:/usr/local/bin"
MANPATH="/usr/man:/usr/local/man"
LD_LIBRARY_PATH="/usr/lib:/usr/local/lib"
OS="`/usr/bin/uname -s | /usr/bin/grep -ci sun`"
}

check_openwindows() {
if [ -d /usr/openwin ]; then
PATH="$PATH:/usr/openwin/bin:/usr/dt/bin"
MANPATH="$MANPATH:/usr/openwin/man:/usr/dt/man"
LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/usr/openwin/lib:/usr/dt/lib"
fi
}

check_build_environment() {
if [ -d /usr/ccs ]; then
PATH="$PATH:/usr/ccs/bin"
LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/usr/ccs/lib"
fi
}

check_online_disk_suite() {
if [ -d /usr/opt/SUNWmd ]; then
PATH="$PATH:/usr/opt/SUNWmd/sbin"
MANPATH="$MANPATH:/usr/opt/SUNWmd/man"
fi
}

check_veritas_volume_manager() {
# Version 2.x
if [ -x /opt/VRTSvxva/bin/vxva ]; then
PATH="$PATH:/opt/VRTSvxva/bin"
MANPATH="$MANPATH:/opt/VRTSvxva/man"
fi

# Version 3.x
if [ -x /opt/VRTSvmsa/bin/vmsa ]; then
PATH="$PATH:/opt/VRTSvmsa/bin"
MANPATH="$MANPATH:/opt/VRTSvxvm/man:/opt/VRTSvmsa/man"
fi
}

check_sun_ent_volume_manager() {
if [ -d /opt/SUNWvxva ]; then
PATH="$PATH:/opt/SUNWvxva/bin"
MANPATH="$MANPATH:/opt/SUNWvxvm/man:/opt/SUNWvxva/man"
fi
}

check_naviscore() {
if [ -d /opt/CascadeView ]; then
. /opt/CascadeView/etc/cvdb.cfg
. /opt/CascadeView/etc/cascadeview.cfg
. /opt/sybase/.sybenv

PATH="$PATH:/opt/OV/bin"
XUSERFILESEARCHPATH="/opt/CascadeView/app-defaults/%N:$XUSERFILESEARCHPATH"

export XUSERFILESEARCHPATH
fi
}

check_networker() {
if [ -d /usr/bin/nsr ]; then
PATH="$PATH:/usr/bin/nsr:/usr/sbin/nsr"
fi
}

check_cluster() {
if [ -d /opt/SUNWcluster ]; then
PATH="$PATH:/opt/SUNWcluster/bin"
MANPATH="$MANPATH:/opt/SUNWcluster/man"
fi
}

generate_paths() {
default_paths
check_openwindows
check_build_environment
check_online_disk_suite
check_veritas_volume_manager
check_sun_ent_volume_manager
check_naviscore
check_networker
check_cluster
}

set_options() {
case "$1" in
*ksh)
EDITOR="vi"
ENV=".kshrc"
HOSTNAME=`/usr/bin/uname -n | /usr/bin/cut -d. -f1`
PAGER="/usr/bin/more"
if [ $OS -gt 0 ]; then
USER=`/usr/xpg4/bin/id -un`
else
USER=`id -un`
fi
;;
*sh)
EDITOR="vi"
HOSTNAME=`/usr/bin/uname -n | /usr/bin/cut -d. -f1`
PAGER="/usr/bin/more"
cd() {
chdir $*
set_prompt `basename $0`
}
if [ $OS -gt 0 ]; then
USER=`/usr/xpg4/bin/id -un`
else
USER=`id -un`
fi
;;
esac
}

set_prompt() {
case "$1" in
-ksh)
PS1='[$USER@$HOSTNAME]:$PWD
# '
;;
-sh)
PWD=`pwd`
PS1="[$USER@$HOSTNAME]:$PWD
# "
;;
esac
}

export_environment() {
export ENV PAGER HOSTNAME LD_LIBRARY_PATH MANPATH PAGER PATH PS1
}

# begin environment

generate_paths
set_options "$0"
set_prompt "$0"
export_environment

# proceed to $ENV for ksh resources

Keep Ryan's name in it - he did write it afterall.

[Feb 1, 2006] Sys Admin v15, i02 Implementing Standard Login Scripts by John Spurgeon and Ed Schaefer

Consider a server model where numerous Unix servers are distributed across numerous production sites hosting database engines and other software applications. Also, assume that only the local systems administrators have command-line access. We think standardizing the administrator's login scripts is a good way to maintain high application availability.

We could implement standard login scripts via skeleton directories. In the Solaris environment, the useradd command provides the -k option, which specifies a skeleton directory. Files from a skeleton directory, such as .profile, are copied into users' home directories when new accounts are created.

There are two reasons we shy away from using skeleton directories to standardize login scripts. First, it can be difficult to make changes to scripts once users have been added. Not only do files in the skeleton directories have to be modified, but all of the existing users' scripts have to be updated, too. Second, we did not want to give users access to the logic responsible for setting up the majority of their environment, and we thought that preventing users from modifying $HOME/.profile was too restrictive.

Instead, we placed the necessary environment setup commands in two special files: /etc/profile and /etc/.kshrc. When a user logs in, the program called "login" spawns a shell -- typically the Korn shell on our servers. The Korn shell looks for login scripts /etc/profile and $HOME/.profile and executes them if they exist. The Korn shell also looks for the file referenced by the environment variable ENV (set to /etc/.kshrc on our servers) and executes it if it exists; this happens whenever the Korn shell is invoked -- not just at login time.

Listing 1 shows what /etc/profile looks like on all of our servers.

# /etc/profile

. /opt/logins/bin/disable_interrupts

umask 022
ulimit -n 1024
. /etc/setenv_path
. /etc/setenv_true_false

if [ `tty` = /dev/console ]
then
   TERM=AT386
   export TERM
fi

case $LOGNAME in
keysync | pwadmin | entry | ontape-c)
    ;;
*)
    . /etc/setenv_informix
    . /etc/setenv_ifics
    readonly ENVFILE=/etc/.kshrc
    readonly ENV='${ENVFILE[(_$-=1)+(_=0)-(_$-!=_${-%%*i*})]}'
    export ENVFILE ENV
    ;;
esac

. /opt/logins/bin/enable_interrupts
# end Listing 1

Note the use of the "dot" command to source files, such as /etc/setenv_path. Modularizing our login scripts this way keeps them short and easy to read. Another feature of our login scripts is the use of the readonly function to protect the value of certain variables, such as ENV.

The most interesting thing about /etc/profile is the way ENV is set:

readonly ENV='${ENVFILE[(_$-=1)+(_=0)-(_$-!=_${-%%*i*})]}'

This code evaluates to a two-position array: ENVFILE[0]=/etc/.kshrc and ENVFILE[1] is null. When a shell is interactive, ENVFILE[0] executes, thus setting the commands in /etc/.kshrc. Obviously, a non-interactive shell does nothing since ENVFILE[1] is null. For a more detailed explanation, see:

http://docs.hp.com/en/B2355-90046/ch23s02.html

Recall that the file referenced by $ENV is executed every time a new shell spawns. This can lead to inefficiencies if a file like /etc/.kshrc contains commands that only need to be executed at login time. This complicated way of setting ENV prevents /etc/.kshrc from being read when the shell is not in interactive mode.

Listing 2 is our /etc/.kshrc file. Like /etc/profile, it is also a short script due to the use of several dot commands.

# /etc/.kshrc

if [[ -o interactive ]]
then
    . /opt/logins/bin/disable_interrupts

    . /etc/setenv_path
    . /etc/setenv_true_false
    . /etc/setenv_informix
    . /etc/setenv_ifics
    . /etc/setenv_user

    . /opt/logins/bin/sh_history.initialize
    . /opt/logins/bin/login_alert
    /opt/logins/bin/greeting
    trap "/etc/.logout" 0

    . /opt/logins/bin/enable_interrupts
fi

# end Listing 2

The script begins with the following if statement:

if [[ -o interactive ]]

This is a simple way to test for an interactive shell. The if statement probably isn't necessary, because it has essentially the same effect as setting ENV the way we did. If you're bothered by inefficiencies, choose one technique or the other. If you're paranoid that something could go wrong with the ENV approach, you may want to use both.

We don't include full listings of all the dot scripts shown in /etc/profile and /etc/.kshrc, since many of them are peculiar to our environment. However, a few are worth sharing.

Listing 3, /opt/logins/bin/disable_interrupts,

# /opt/logins/bin/disable_interrupts
trap "exit 1" 1 2 3 9 15 16 17

if [[ -o interactive ]]
then
    stty -isig
    stty intr ''
    stty quit  ''
    stty erase '^H'
    stty kill ''
    stty eof ''
    stty eol ''
    stty eol2 ''
    stty swtch ''
    stty start ''
    stty stop ''
    stty susp ''
    stty dsusp ''
    stty rprnt ''
    stty flush ''
    stty werase ''
    stty lnext ''
fi
# end Listing 3

and Listing 4, /opt/logins/bin/enable_interrupts,

# /opt/logins/bin/enable_interrupts

stty sane
stty istrip
stty erase '^h'
stty quit '^\'
stty susp '^z'
stty intr '^c'

trap 1 2 3 9 15 16 17
# end Listing 4

are two scripts we use to manipulate the environment during the login process to prevent users from interrupting the login scripts and gaining premature access to a command line.

Listing 5 is a file we created named setenv_user.

# /etc/setenv_user

REAL_USER=`/usr/xpg4/bin/id -urn`
EFFECTIVE_USER=`/usr/xpg4/bin/id -un`
TERM_USER=`/usr/bin/who -m | /usr/bin/cut -d' ' -f1`
export REAL_USER EFFECTIVE_USER TERM_USER

TERM=${TERM:=AT386}
MAIL=/usr/mail/${REAL_USER:-anonymous}
PAGER=/usr/local/bin/less
LESS="-P-Less- %pb\%"
LESSSECURE=1
EDITOR=/usr/bin/vi
VISUAL=/usr/bin/vi
EXINIT="set showmode tabstop=4"

if [ "$REAL_USER" != "$TERM_USER" ]
then
        PS1=${REAL_USER:-anonymous}"("${TERM_USER:-anonymous}")"@`uname -n`':${PWD} % '
else
        PS1=${REAL_USER:-anonymous}@`uname -n`':${PWD} % '
fi

PS2='% '
PS4='$0 line ${LINENO}: '
WWW_HOME=/opt/docs/html/index.html
export TERM MAIL PAGER LESS LESSSECURE EDITOR VISUAL EXINIT \
  PS1 PS2 PS4 WWW_HOME

alias pd=pushd
alias help=lynx

# end /etc/setenv_user

In setenv_user, we set and export some custom environment variables, such as REAL_USER and EFFECTIVE_USER, as well as several common variables, such as TERM, MAIL, PAGER, LESS, PS1, and PS2.

Finally, note the following command in /etc/.kshrc:

trap "/etc/.logout" 0

This trap statement causes the shell to execute the command /etc/.logout when the shell exists.

Login scripts need to be tailored to the requirements of your environment and the preferences of your users. The approach we've taken to managing our login scripts won't work for everyone. But, hopefully, we've presented a few useful techniques -- some of which you might want to adopt.

Our next column builds upon our custom login idea. We present a method for archiving individual user's history files by manipulating shell variable HISTFILE.

References

Hewlett Packard. 1992. SHELLS: User's Guide, HP 9000 Computers. Palo Alto, CA. -- http://docs.hp.com/en/B2355-90046/ch23s02.html

[Feb 19, 2001] A brief introduction to the bash shell -- contains two sample bash dot files for C shell users

A sample annotated ~/.bash_profile

This file is executed when you first login, the variables are all exported so that they are available to all subshells.

This has a bit of tricky programming in it where all of the paths are stored in separate files - so that they can be easily changed without modifying the original ~/.bash_profile file.

# ~/.bash_profile
# Executed by login shells

# Converts a \n separated list into a colon separated list
colonise() {
        /bin/cat $1 | /bin/tr "\012" ":"
}

### Variables used by bash itself

# Paths...
# these all use the above "colonise" function to
# convert a list of paths on separate lines into
# a colon separated list.
export PATH=`colonise ~/.path`
export MANPATH=`colonise ~/.manpath`
export MAILPATH=`colonise ~/.mailpath`
export CDPATH=`colonise ~/.cdpath`

# Control history
# I don't like to have a lot of 
# old commands hanging around.
export HISTFILESIZE=100
export HISTSIZE=10
export HISTCONTROL=ignoreboth

# Control file name completion: ignore the following suffixes
export FIGNORE=`colonise ~/.fignore`

# Exiting bash deliberately and involuntarily
# export IGNOREEOF=1
export TMOUT=3600

# Prompt
export PS1="\u@\h \W [\!]\$: "

### Variables that don't relate to bash

# Set variables for a warm fuzzy environment
export CVSROOT=~/.cvsroot
export PGPPATH=~/.pgp
export EDITOR=/usr/local/bin/emacs
export PAGER=/usr/local/bin/less
export PRINTER=134

# Execute the subshell script
source ~/.bashrc

# end of ~/.bash_profile

A sample ~/.bashrc which is executed each time a shell or subshell is started. It just contains aliases, some functions and a couple of miscellaneous settings.

# ~/.bashrc 
# executed by login and subshells

# aliases

# search man pages by subject
alias a='man -k'

# edit and re-read this file
alias be='$EDITOR ~/.bashrc ; source ~/.bashrc'

# add the current directory to the "cdpath"
alias cdpath='pwd >> ~/.cdpath ; export CDPATH=`colonise ~/.cdpath`'

# abbreviations for some common commands
alias f=finger
alias h=history
alias j=jobs
alias l='ls -lF'
alias la='ls -alF'
alias lo=logout
alias ls='ls -F'
alias m='less -a -i -P='

# functions

# A new version of "cd" which
# prints the directory after cd'ing
cd() {
        builtin cd $1
        pwd
}
# add the directoried specified to the path file and re-read it.
pathadd() {
        for p in $*
        do
                echo $p >> ~/.path
        done
        export PATH=`colonise ~/.path`
}


# Other settings
umask 027
mesg y

# end of ~/.bashrc 
# Uncomment the following if you prefer vi style command editing 
# to emacs style

# set +o emacs
# set -o vi

# Important startup procedures...
/usr/local/games/bin/fortune
echo

# end of ~/.bashrc

You can also create a ~/.bash_logout file that is executed whenever you log out.

[Jan 14, 2000] Dot files by Juhapekka Tolvanen <juhtolv@st.jyu.fi> Thanks Juhapekka


[May 16, 1999] script.hints

[ May 16, 1999] Startup FAQ for Csh & Tcsh


Recommended Links

Softpanorama hot topic of the month

Softpanorama Recommended


Controlling the prompt in bash

The value of the variable $PROMPT_COMMAND is examined just before Bash prints each primary prompt. If it is set and non-null, then the value is executed just as if you had typed it on the command line. In addition, the following table describes the special characters which can appear in the PS1 variable:

\t
the time, in HH:MM:SS format.
\d
the date, in "Weekday Month Date" format (e.g. "Tue May 26").
\n
newline.
\s
the name of the shell, the basename of $0 (the portion following the final slash).
\w
the current working directory.
\W
the basename of $PWD.
\u
your username.
\h
the hostname.
\#
the command number of this command.
\!
the history number of this command.
\nnn
the character corresponding to the octal number nnn.
\$
if the effective uid is 0, #, otherwise $.
\\
a backslash.
\[
begin a sequence of non-printing characters. This could be used to embed a terminal control sequence into the prompt.
\]
end a sequence of non-printing characters.



Etc

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available in our efforts to advance understanding of environmental, political, human rights, economic, democracy, scientific, and social justice issues, etc. We believe this constitutes a 'fair use' of any such copyrighted material as provided for in section 107 of the US Copyright Law. In accordance with Title 17 U.S.C. Section 107, the material on this site is distributed without profit exclusivly for research and educational purposes.   If you wish to use copyrighted material from this site for purposes of your own that go beyond 'fair use', you must obtain permission from the copyright owner. 

ABUSE: IPs or network segments from which we detect a stream of probes might be blocked for no less then 90 days. Multiple types of probes increase this period.  

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least


Copyright © 1996-2016 by Dr. Nikolai Bezroukov. www.softpanorama.org was created as a service to the UN Sustainable Development Networking Programme (SDNP) in the author free time. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License.

The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to make a contribution, supporting development of this site and speed up access. In case softpanorama.org is down you can use the at softpanorama.info

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the author present and former employers, SDNP or any other organization the author may be associated with. We do not warrant the correctness of the information provided or its fitness for any purpose.

Last modified: February 14, 2017