.bashrc Beispiele

By commandlineFu 09.12.2021

bash-logo

Applying changes

To apply changes from this article to your .bashrc (without ending subshells), do:

$ source ~/.bashrc
  oder
$ . .bashrc

Or, if you want, you can build your prompt using the ✓ unicode symbol for a zero status and the ✗ unicode symbol for a nonzero status:

0[email protected] ~ $ true
0[email protected] ~ $ false
1[email protected] ~ $ I will try to type a wrong command...
bash: I will try to type a wrong command...: command not found
127[email protected] ~ $ _

# return value visualisation

PS1="[33[01;37m]$? $(if [[ $? == 0 ]]; 
then echo "[33[01;32m]342234223"; 
else echo "[33[01;31m]342234227"; fi) $(if [[ ${EUID} == 0 ]]; 
then echo '[33[01;31m]h'; 
else echo '[33[01;32m][email protected]'; fi)[33[01;34m] w $[33[00m] "

Alternatively, this can be made more readable with `PROMPT_COMMAND`:

set_prompt () {
    Last_Command=$? # Must come first!
    Blue='[e[01;34m]'
    White='[e[01;37m]'
    Red='[e[01;31m]'
    Green='[e[01;32m]'
    Reset='[e[00m]'
    FancyX='342234227'
    Checkmark='342234223'

## Add a bright white exit status for the last command

    PS1="$White$? "
    # If it was successful, print a green check mark. Otherwise, print
    # a red X.
    if [[ $Last_Command == 0 ]]; then
        PS1+="$Green$Checkmark "
    else
        PS1+="$Red$FancyX "
    fi
    # If root, just print the host in red. Otherwise, print the current user
    # and host in green.
    if [[ $EUID == 0 ]]; then
        PS1+="$Redh "
    else
        PS1+="$Greenu@h "
    fi
    # Print the working directory and prompt marker in blue, and reset
    # the text color to the default.
    PS1+="$Bluew $$Reset "
}
PROMPT_COMMAND='set_prompt'

Here's an alternative that only includes the error status, if _non-zero_:

PROMPT_COMMAND='es=$?; [[ $es -eq 0 ]] && unset error || error=$(echo -e "e[1;41m $es e[40m")'
PS1="${error} ${PS1}"

Tips and tricks

Different colors for text entry and console output

If you do not reset the text color at the end of your prompt, both the text you enter and the console text will simply stay in that color. If you want to edit text in a special color but still use the default color for command output, you will need to reset the color after you press Enter, but still before any commands get run. You can do this by installing a DEBUG trap, like this:

~/.bashrc trap ‘echo -ne “e[0m”’ DEBUG

Random quotations at logon

For a brown Fortune prompt, add:

~/.bashrc
[[ "$PS1" ]] && echo -e "e[00;33m$(/usr/bin/fortune)e[00m"

 

~/.bashrc
# Arch latest news
if [ "$PS1" ] && [[ $(ping -c1 www.google.com 2>&-) ]]; then
 # The characters "£, §" are used as metacharacters. They should not be encountered in a feed...
 echo -e "$(echo $(curl --silent https://www.archlinux.org/feeds/news/ | sed -e ':a;N;$!ba;s/n/ /g') |
  sed -e 's/&/&/g
  s/&lt;|&#60;/</g
  s/&gt;|&#62;/>/g
  s/</a>/£/g
  s/href="/§/g
  s/<title>/nnn   :: e[01;31m/g; s/</title>/e[00m ::n/g
  s/<link>/ [ e[01;36m/g; s/</link>/e[00m ]/g
  s/<description>/nne[00;37m/g; s/</description>/e[00mnn/g
  s/<p( [^>]*)?>|<brs*/?>/n/g
  s/<b( [^>]*)?>|<strong( [^>]*)?>/e[01;30m/g; s/</b>|</strong>/e[00;37m/g
  s/<i( [^>]*)?>|<em( [^>]*)?>/e[41;37m/g; s/</i>|</em>/e[00;37m/g
  s/<u( [^>]*)?>/e[4;37m/g; s/</u>/e[00;37m/g
  s/<code( [^>]*)?>/e[00m/g; s/</code>/e[00;37m/g
  s/<a[^§|t]*§([^"]*)"[^>]*>([^£]*)[^£]*£/e[01;31m2e[00;37m e[01;34m[e[00;37m e[04m1e[00;37me[01;34m ]e[00;37m/g
  s/<li( [^>]*)?>/n e[01;34m*e[00;37m /g
  s/<![CDATA[|]]>//g
  s/|>s*<//g
  s/ *<[^>]+> */ /g
  s/[<>£§]//g')nn";
fi

To only get the absolute latest item, use this:

# Arch latest news
if [ "$PS1" ] && [[ $(ping -c1 www.google.com 2>&-) ]]; then
 # The characters "£, §" are used as metacharacters. They should not be encountered in a feed...
 echo -e "$(echo $(curl --silent https://www.archlinux.org/feeds/news/ | awk ' NR == 1 {while ($0 !~ /</item>/) {print;getline} sub(/</item>.*/,"</item>") ;print}' | sed -e ':a;N;$!ba;s/n/ /g') |
  sed -e 's/&amp;/&/g
  s/&lt;|&#60;/</g
  s/&gt;|&#62;/>/g
  s/</a>/£/g
  s/href="/§/g
  s/<title>/nnn   :: e[01;31m/g; s/</title>/e[00m ::n/g
  s/<link>/ [ e[01;36m/g; s/</link>/e[00m ]/g
  s/<description>/nne[00;37m/g; s/</description>/e[00mnn/g
  s/<p( [^>]*)?>|<brs*/?>/n/g
  s/<b( [^>]*)?>|<strong( [^>]*)?>/e[01;30m/g; s/</b>|</strong>/e[00;37m/g
  s/<i( [^>]*)?>|<em( [^>]*)?>/e[41;37m/g; s/</i>|</em>/e[00;37m/g
  s/<u( [^>]*)?>/e[4;37m/g; s/</u>/e[00;37m/g
  s/<code( [^>]*)?>/e[00m/g; s/</code>/e[00;37m/g
  s/<a[^§|t]*§([^"]*)"[^>]*>([^£]*)[^£]*£/e[01;31m2e[00;37m e[01;34m[e[00;37m e[04m1e[00;37me[01;34m ]e[00;37m/g
  s/<li( [^>]*)?>/n e[01;34m*e[00;37m /g
  s/<![CDATA[|]]>//g
  s/|>s*<//g
  s/ *<[^>]+> */ /g
  s/[<>£§]//g')nn";
fi

### Colors overview

The page at [ascii-table.com](http://ascii-table.com/ansi-escape-sequences.php) describes the various available color escapes. The following Bash function displays a table with ready-to-copy escape codes.

~/.bashrc
colors() {
 local fgc bgc vals seq0
printf "Color escapes are %sn" 'e[${value};...;${value}m'
 printf "Values 30..37 are e[33mforeground colorse[mn"
 printf "Values 40..47 are e[43mbackground colorse[mn"
 printf "Value  1 gives a  e[1mbold-faced looke[mnn"
 # foreground colors
 for fgc in {30..37}; do
  # background colors
  for bgc in {40..47}; do
   fgc=${fgc#37} # white
   bgc=${bgc#40} # black
vals="${fgc:+$fgc;}${bgc}"
   vals=${vals%%;}
seq0="${vals:+e[${vals}m}"
   printf "  %-9s" "${seq0:-(default)}"
   printf " ${seq0}TEXTe[m"
   printf " e[${vals:+${vals+$vals;}}1mBOLDe[m"
  done
  echo; echo
 done
}

### Syntax Highlighting im vi

Der Texteditor vi auf der Konsole, der in keinem LINUX/UNIX fehlt, ist in den modernen Linuxsystemen auf einen wesentlich leistungsfähigeren Nachfolger [**vim**](http://www.vim.org/) oder einen Klon davon, gelinkt. Dieser Editor kann unter Anderem auch **Syntax Highlighting"** für eine Vielzahl von Dateitypen. Im Verzeichnis _/usr/share/vim/current/syntax/_ stehen die Syntaxkonfigurationsfiles. Anhand der Endung (prefix) der zu editierenden Datei erkennt vim welche Syntax für diesen Dateitype zu benutzen ist. Selbstverständlich kann man auch seine eigenen Syntax-Konfigurationsfiles entwerfen und einsetzen und auch die Farben anpassen. Siehe dazu [vimdoc.sourceforge.net](http://vimdoc.sourceforge.net/htmldoc/usr_44.html)

#### Ein- Ausschalten des Syntax highlighting im vim

permanent durch Eintrag in der Vim-Konfigurationsdatei ~/.vimrc

anlegen der Datei bzw. erweitern dieser Datei und folgenden Eintrag vornehmen

**syntax on**

bei Bedarf durch Zeilenoption beim Start von vi

# vi +**"syn on"** file.prefix

bei Bedarf während der Sitzung im Kommandomodus

hier kann während der Sitzung dieser Modus nach Belieben Ein- und Ausgeschaltet werden

:syntax on

Analog Ausschalten

:syntax off

* * *

So I’ve found the following cool Bash prompt:

Bash prompt

..with the very basic logic of:

PS1="[33[01;37m]$? $(if [[ $? == 0 ]]; 
then echo "[33[01;32m]342234223"; 
else echo "[33[01;31m]342234227"; fi) $(if [[ ${EUID} == 0 ]]; 
then echo '[33[01;31m]h'; else echo '[33[01;32m][email protected]'; fi)[33[01;34m] w $[33[00m] "

However, this is not very basic and happens to be an incredible mess. I’d like to make it more readable.

Use PROMPT_COMMAND to build the value up in a sane fashion. This saves a lot of quoting and makes the text much more readable. Note that you can use e instead of 33 to represent the escape character inside a prompt.

set_prompt () {
    local last_command=$?  # Must come first!
    PS1=""
    # Add a bright white exit status for the last command
    PS1+='[e[01;37m]$? '
    # If it was successful, print a green check mark. Otherwise, print
    # a red X.
    if [[ $last_command == 0 ]]; then
        PS1+='[e[01;32m]342234223 '
    else
        PS1+='[e[01;31m]342234227 '
    fi
    # If root, just print the host in red. Otherwise, print the current user
    # and host in green.
    # in
    if [[ $EUID == 0 ]]; then
        PS1+='[e[01;31m]h '
    else
        PS1+='[e[01;32m][email protected] '
    fi
    # Print the working directory and prompt marker in blue, and reset
    # the text color to the default.
    PS1+='[e[01;34m] w $[e[00m] '
}
PROMPT_COMMAND='set_prompt'

You can define variables for the more esoteric escape sequences, at the cost of needing some extra escapes inside the double quotes, to accommodate parameter expansion.

set_prompt () {
    local last_command=$? # Must come first!
    PS1=""
    local blue='[e[01;34m]'
    local white='[e[01;37m]'
    local red='[e[01;31m]'
    local green='[e[01;32m]'
    local reset='[e[00m]'
    local fancyX='342234227'
    local checkmark='342234223'

# =============================================================== #
   #
   # PERSONAL $HOME/.bashrc FILE for bash-3.0 (or later)
   # By Emmanuel Rouat [no-email]
   #
   # Last modified: Tue Nov 20 22:04:47 CET 2012
#  This file is normally read 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 often 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
   #
   #  The choice of colors was done for a shell with a dark background
   #+ (white on black), and this is usually also suited for pure text-mode
   #+ consoles (no X server available). If you use a white background,
   #+ you'll have to do some other choices for readability.
   #
   #  This bashrc file is a bit overcrowded.
   #  Remember, it is just just an example.
   #  Tailor it to your needs.
   #
   # =============================================================== #
# --&gt; Comments added by HOWTO author.
# If not running interactively, don't do anything
   [ -z "$PS1" ] &amp;&amp; return
#-------------------------------------------------------------
   # Source global definitions (if any)
   #-------------------------------------------------------------
if [ -f /etc/bashrc ]; then
   . /etc/bashrc   # --&gt; Read /etc/bashrc, if present.
   fi
#--------------------------------------------------------------
   #  Automatic setting of $DISPLAY (if not set already).
   #  This works for me - 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) - however this code seems to work in a majority
   #+ of cases.
   #--------------------------------------------------------------
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
   #-------------------------------------------------------------
#set -o nounset     # These  two options are useful for debugging.
   #set -o xtrace
   alias debug="set -o nounset; set -o xtrace"
ulimit -S -c 0      # Don't want coredumps.
   set -o notify
   set -o noclobber
   set -o ignoreeof
# 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.
#-------------------------------------------------------------
   # Greeting, motd etc. ...
   #-------------------------------------------------------------
# Color definitions (taken from Color Bash Prompt HowTo).
   # Some colors might look different of some terminals.
   # For example, I see 'Bold Red' as 'orange' on my screen,
   # hence the 'Green' 'BRed' 'Red' sequence I often use in my prompt.
# Normal Colors
   Black='e[0;30m'        # Black
   Red='e[0;31m'          # Red
   Green='e[0;32m'        # Green
   Yellow='e[0;33m'       # Yellow
   Blue='e[0;34m'         # Blue
   Purple='e[0;35m'       # Purple
   Cyan='e[0;36m'         # Cyan
   White='e[0;37m'        # White
# Bold
   BBlack='e[1;30m'       # Black
   BRed='e[1;31m'         # Red
   BGreen='e[1;32m'       # Green
   BYellow='e[1;33m'      # Yellow
   BBlue='e[1;34m'        # Blue
   BPurple='e[1;35m'      # Purple
   BCyan='e[1;36m'        # Cyan
   BWhite='e[1;37m'       # White
# Background
   On_Black='e[40m'       # Black
   On_Red='e[41m'         # Red
   On_Green='e[42m'       # Green
   On_Yellow='e[43m'      # Yellow
   On_Blue='e[44m'        # Blue
   On_Purple='e[45m'      # Purple
   On_Cyan='e[46m'        # Cyan
   On_White='e[47m'       # White
NC="e[m"               # Color Reset
ALERT=${BWhite}${On_Red} # Bold White on red background
echo -e "${BCyan}This is BASH ${BRed}${BASH_VERSION%.*}${BCyan}
   - DISPLAY on ${BRed}$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 "${BRed}Hasta la vista, baby${NC}"
      }
      trap _exit EXIT
#-------------------------------------------------------------
   # Shell Prompt - for many examples, see:
   #       http://www.debian-administration.org/articles/205
   #       http://www.askapache.com/linux/bash-power-prompt.html
   #       http://tldp.org/HOWTO/Bash-Prompt-HOWTO
   #       https://github.com/nojhan/liquidprompt
   #-------------------------------------------------------------
   # Current Format: [TIME [email protected] PWD] &gt;
   # TIME:
   #    Green     == machine load is low
   #    Orange    == machine load is medium
   #    Red       == machine load is high
   #    ALERT     == machine load is very high
   # USER:
   #    Cyan      == normal user
   #    Orange    == SU to user
   #    Red       == root
   # HOST:
   #    Cyan      == local session
   #    Green     == secured remote connection (via ssh)
   #    Red       == unsecured remote connection
   # PWD:
   #    Green     == more than 10% free disk space
   #    Orange    == less than 10% free disk space
   #    ALERT     == less than 5% free disk space
   #    Red       == current user does not have write privileges
   #    Cyan      == current filesystem is size zero (like /proc)
   # &gt;:
   #    White     == no background or suspended jobs in this shell
   #    Cyan      == at least one background job in this shell
   #    Orange    == at least one suspended job in this shell
   #
   #    Command is added to the history file each time you hit enter,
   #    so it's available to all shells (using 'history -a').
# Test connection type:
   if [ -n "${SSH_CONNECTION}" ]; then
   CNX=${Green}        # Connected on remote machine, via ssh (good).
   elif [[ "${DISPLAY%%:0*}" != "" ]]; then
   CNX=${ALERT}        # Connected on remote machine, not via ssh (bad).
   else
   CNX=${BCyan}        # Connected on local machine.
   fi
# Test user type:
   if [[ ${USER} == "root" ]]; then
   SU=${Red}           # User is root.
   elif [[ ${USER} != $(logname) ]]; then
   SU=${BRed}          # User is not login user.
   else
   SU=${BCyan}         # User is normal (well ... most of us are).
   fi
NCPU=$(grep -c 'processor' /proc/cpuinfo)    # Number of CPUs
   SLOAD=$(( 100*${NCPU} ))        # Small load
   MLOAD=$(( 200*${NCPU} ))        # Medium load
   XLOAD=$(( 400*${NCPU} ))        # Xlarge load
# Returns system load as percentage, i.e., '40' rather than '0.40)'.
   function load()
   {
   local SYSLOAD=$(cut -d " " -f1 /proc/loadavg | tr -d '.')
   # System load of the current host.
   echo $((10#$SYSLOAD))       # Convert to decimal.
   }
# Returns a color indicating system load.
   function load_color()
   {
   local SYSLOAD=$(load)
   if [ ${SYSLOAD} -gt ${XLOAD} ]; then
   echo -en ${ALERT}
   elif [ ${SYSLOAD} -gt ${MLOAD} ]; then
   echo -en ${Red}
   elif [ ${SYSLOAD} -gt ${SLOAD} ]; then
   echo -en ${BRed}
   else
   echo -en ${Green}
   fi
   }
# Returns a color according to free disk space in $PWD.
   function disk_color()
   {
   if [ ! -w "${PWD}" ] ; then
   echo -en ${Red}
   # No 'write' privilege in the current directory.
   elif [ -s "${PWD}" ] ; then
   local used=$(command df -P "$PWD" |
   awk 'END {print $5} {sub(/%/,"")}')
   if [ ${used} -gt 95 ]; then
   echo -en ${ALERT}           # Disk almost full (&gt;95%).
   elif [ ${used} -gt 90 ]; then
   echo -en ${BRed}            # Free disk space almost gone.
   else
   echo -en ${Green}           # Free disk space is ok.
   fi
   else
   echo -en ${Cyan}
   # Current directory is size '0' (like /proc, /sys etc).
   fi
   }
# Returns a color according to running/suspended jobs.
   function job_color()
   {
   if [ $(jobs -s | wc -l) -gt "0" ]; then
   echo -en ${BRed}
   elif [ $(jobs -r | wc -l) -gt "0" ] ; then
   echo -en ${BCyan}
   fi
   }
# Adds some text in the terminal frame (if applicable).
# Now we construct the prompt.
   PROMPT_COMMAND="history -a"
   case ${TERM} in
   *term | rxvt | linux)
   PS1="[$(load_color)][A[${NC}] "
   # Time of day (with load info):
   PS1="[$(load_color)][A[${NC}] "
   # [email protected] (with connection type info):
   PS1=${PS1}"[${SU}]u[${NC}]@[${CNX}]h[${NC}] "
   # PWD (with 'disk space' info):
   PS1=${PS1}"[$(disk_color)]W][${NC}] "
   # Prompt (with 'job' info):
   PS1=${PS1}"[$(job_color)]&gt;[${NC}] "
   # Set title of current xterm:
   PS1=${PS1}"[e]0;[[email protected]] wa]"
   ;;
   *)
   PS1="(A [email protected] W) &gt; " # --&gt; PS1="(A [email protected] w) &gt; "
   # --&gt; Shows full pathname of current dir.
   ;;
   esac
export TIMEFORMAT=$'nreal %3Rtuser %3Utsys %3Stpcpu %Pn'
   export HISTIGNORE="&amp;:bg:fg:ll:h"
   export HISTTIMEFORMAT="$(echo -e ${BCyan})[%d/%m %H:%M:%S]$(echo -e ${NC}) "
   export HISTCONTROL=ignoredups
   export HOSTFILE=$HOME/.hosts    # Put a list of remote hosts in ~/.hosts
#============================================================
   #
   #  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.
   #
   #============================================================
#-------------------
   # Personnal Aliases
   #-------------------
alias rm='rm -i'
   alias cp='cp -i'
   alias mv='mv -i'
   # -&gt; Prevents accidentally clobbering files.
   alias mkdir='mkdir -p'
alias h='history'
   alias j='jobs -l'
   alias which='type -a'
   alias ..='cd ..'
# Pretty-print of some PATH variables:
   alias path='echo -e ${PATH//:/n}'
   alias libpath='echo -e ${LD_LIBRARY_PATH//:/n}'
alias du='du -kh'    # Makes a more readable output.
   alias df='df -kTh'
#-------------------------------------------------------------
   # The 'ls' family (this assumes you use a recent GNU ls).
   #-------------------------------------------------------------
   # Add colors for filetype and  human-readable sizes by default on 'ls':
   alias ls='ls -h --color'
   alias lx='ls -lXB'         #  Sort by extension.
   alias lk='ls -lSr'         #  Sort by size, biggest last.
   alias lt='ls -ltr'         #  Sort by date, most recent last.
   alias lc='ls -ltcr'        #  Sort by/show change time,most recent last.
   alias lu='ls -ltur'        #  Sort by/show access time,most recent last.
# The ubiquitous 'll': directories first, with alphanumeric sorting:
   alias ll="ls -lv --group-directories-first"
   alias lm='ll |more'        #  Pipe through 'more'
   alias lr='ll -R'           #  Recursive ls.
   alias la='ll -A'           #  Show hidden files.
   alias tree='tree -Csuh'    #  Nice alternative to 'recursive ls' ...
#-------------------------------------------------------------
   # Tailoring 'less'
   #-------------------------------------------------------------
alias more='less'
   export PAGER=less
   export LESSCHARSET='latin1'
   export LESSOPEN='|/usr/bin/lesspipe.sh %s 2&gt;&amp;-'
   # 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:-...'
# LESS man page colors (makes Man pages more readable).
   export LESS_TERMCAP_mb=$'E[01;31m'
   export LESS_TERMCAP_md=$'E[01;31m'
   export LESS_TERMCAP_me=$'E[0m'
   export LESS_TERMCAP_se=$'E[0m'
   export LESS_TERMCAP_so=$'E[01;44;33m'
   export LESS_TERMCAP_ue=$'E[0m'
   export LESS_TERMCAP_us=$'E[01;32m'
#-------------------------------------------------------------
   # 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
   #-------------------------------------------------------------
# Adds some text in the terminal frame (if applicable).
function xtitle()
   {
   case "$TERM" in
   *term* | rxvt)
   echo -en  "e]0;$*a" ;;
   *)  ;;
   esac
   }
# Aliases that use xtitle
   alias top='xtitle Processes on $HOST &amp;&amp; top'
   alias make='xtitle Making $(basename $PWD) ; make'
# .. and functions
   function man()
   {
   for i ; do
   xtitle The $(basename $1|tr -d .[:digit:]) manual
   command man -a "$i"
   done
   }
#-------------------------------------------------------------
   # Make the following commands run in background automatically:
   #-------------------------------------------------------------
function te()  # wrapper around xemacs/gnuserv
   {
   if [ "$(gnuclient -batch -eval t 2&gt;&amp;-)" == "t" ]; then
   gnuclient -q "[email protected]";
   else
   ( xemacs "[email protected]" &amp;);
   fi
   }
function soffice() { command soffice "[email protected]" &amp; }
   function firefox() { command firefox "[email protected]" &amp; }
   function xpdf() { command xpdf "[email protected]" &amp; }
#-------------------------------------------------------------
   # File &amp; strings 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 mycase=""
   local usage="fstr: find string in files.
   Usage: fstr [-i] "pattern" ["filename pattern"] "
   while getopts :it opt
   do
   case "$opt" in
   i) mycase="-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&gt;&amp;- | more
}
function swap()
   { # Swap 2 filenames around, if they exist (from Uzi's bashrc).
   local TMPFILE=tmp.$$
[ $# -ne 2 ] &amp;&amp; echo "swap: 2 arguments needed" &amp;&amp; return 1
   [ ! -e $1 ] &amp;&amp; echo "swap: $1 does not exist" &amp;&amp; return 1
   [ ! -e $2 ] &amp;&amp; echo "swap: $2 does not exist" &amp;&amp; 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 &gt;extract&lt;" ;;
   esac
   else
   echo "'$1' is not a valid file!"
   fi
   }
# Creates an archive (*.tar.gz) from given directory.
   function maketar() { tar cvzf "${1%%/}.tar.gz"  "${1%%/}/"; }
# Create a ZIP archive of a file or folder.
   function makezip() { zip -r "${1%%/}.zip" "$1" ; }
# Make your directories and files access rights sane.
   function sanitize() { chmod -R u=rwX,g=rX,o= "[email protected]" ;}
#-------------------------------------------------------------
   # Process/system related functions:
   #-------------------------------------------------------------
function my_ps() { ps [email protected] -u $USER -o pid,%cpu,%mem,bsdtime,command ; }
   function pp() { my_ps f | awk '!/awk/ &amp;&amp; $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/ &amp;&amp; $0~pat { print $1 }' pat=${!#} )
   do
   pname=$(my_ps | awk '$1~var { print $5 }' var=$pid )
   if ask "Kill process $pid &lt;$pname&gt; with signal $sig?"
   then kill $sig $pid
   fi
   done
   }
function mydf()         # Pretty-print of 'df' output.
   {                       # Inspired by 'dfc' utility.
   for fs ; do
 if [ ! -d $fs ]
   then
   echo -e $fs" :No such file or directory" ; continue
   fi
 local info=( $(command df -P $fs | awk 'END{ print $2,$3,$5 }') )
   local free=( $(command df -Pkh $fs | awk 'END{ print $4 }') )
   local nbstars=$(( 20 * ${info[1]} / ${info[0]} ))
   local out="["
   for ((j=0;j&lt;20;j++)); do
   if [ ${j} -lt ${nbstars} ]; then
   out=$out"*"
   else
   out=$out"-"
   fi
   done
   out=${info[2]}" "$out"] ("$free" free on "$fs")"
   echo -e $out
   done
   }
function my_ip() # Get IP adress on ethernet.
   {
   MY_IP=$(/sbin/ifconfig eth0 | awk '/inet/ { print $2 } ' |
   sed -e s/addr://)
   echo ${MY_IP:-"Not connected"}
   }
function ii()   # Get current host related info.
   {
   echo -e "nYou are logged on ${BRed}$HOST"
   echo -e "n${BRed}Additionnal information:$NC " ; uname -a
   echo -e "n${BRed}Users logged on:$NC " ; w -hs |
   cut -d " " -f1 | sort | uniq
   echo -e "n${BRed}Current date :$NC " ; date
   echo -e "n${BRed}Machine stats :$NC " ; uptime
   echo -e "n${BRed}Memory stats :$NC " ; free
   echo -e "n${BRed}Diskspace :$NC " ; mydf / $HOME
   echo -e "n${BRed}Local IP Address :$NC" ; my_ip
   echo -e "n${BRed}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 &lt;= max ; i++)); do  # --&gt; C-like syntax
   eval "[email protected]";
   done
   }
function ask()          # See 'killps' for example of use.
   {
   echo -n "[email protected]" '[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 SECTION
   #  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 then 3.0 for some features.
   #
   #  Note that most linux distributions now provide many completions
   # 'out of the box' - however, you might need to make your own one day,
   #  so I kept those here as examples.
   #=========================================================================
if [ "${BASH_VERSION%.*}" &lt; "3.0" ]; then
   echo "You will need to upgrade to version 3.0 for full
   programmable completion features"
   return
   fi
shopt -s extglob        # Necessary.
complete -A hostname   rsh rcp telnet rlogin 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 '!*[email protected](@(?(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
   '!*[email protected](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 '!*[email protected](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&gt;/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 &lt; ${#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 ] &amp;&amp; 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 ] &amp;&amp; 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&gt;/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=( $( 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
# Local Variables:
   # mode:shell-script
   # sh-shell:bash
   # End:

 

* * *
### **Example .bash_profile file**

#  ~/.bash_profile:

#  Note that a variable may require special treatment
    #+ if it will be exported.

DARKGRAY='e[1;30m'
    LIGHTRED='e[1;31m'
    GREEN='e[32m'
    YELLOW='e[1;33m'
    LIGHTBLUE='e[1;34m'
    NC='e[m'

PCT="`if [[ $EUID -eq 0 ]]; then T='$LIGHTRED' ; else T='$LIGHTBLUE'; fi;
   echo $T `"

#  For "literal" command substitution to be assigned to a variable,
    #+ use escapes and double quotes:
    #+       PCT="` ... `" . . .
    #  Otherwise, the value of PCT variable is assigned only once,
    #+ when the variable is exported/read from .bash_profile,
    #+ and it will not change afterwards even if the user ID changes.

PS1="n$GREEN[w] n$DARKGRAY($PCTt$DARKGRAY)-($PCTu$DARKGRAY)-($PCT!
   $DARKGRAY)$YELLOW-&gt; $NC"

#  Escape a variables whose value changes:
    #        if [[ $EUID -eq 0 ]],
    #  Otherwise the value of the EUID variable will be assigned only once,
    #+ as above.

#  When a variable is assigned, it should be called escaped:
    #+       echo $T,
    #  Otherwise the value of the T variable is taken from the moment the PCT
    #+ variable is exported/read from .bash_profile.
    #  So, in this example it would be null.

#  When a variable's value contains a semicolon it should be strong quoted:
    #        T='$LIGHTRED',
    #  Otherwise, the semicolon will be interpreted as a command separator.

#  Variables PCT and PS1 can be merged into a new PS1 variable:

PS1="`if [[ $EUID -eq 0 ]]; then PCT='$LIGHTRED';
    else PCT='$LIGHTBLUE'; fi;
    echo 'n$GREEN[w] n$DARKGRAY('$PCT't$DARKGRAY)-
   ('$PCT'u$DARKGRAY)-('$PCT'!$DARKGRAY)$YELLOW-&gt; $NC'`"
# The trick is to use strong quoting for parts of old PS1 variable.

* * *

#######################################################
# 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="[[33[1;34mw[33[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 "[email protected]" [email protected]:/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 ""

 

* * *

30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X

An alias is nothing but shortcut to commands. The alias command allows user to launch any command or group of commands (including options and filenames) by entering a single word. Use alias command to display list of all defined aliases. You can add user defined aliases to ~/.bashrc file. You can cut down typing time with these aliases, work smartly, and increase productivity at the command prompt.

More about aliases

The general syntax for the alias command for the bash shell is as follows.

Task: List aliases

Type the following command:

alias

Sample outputs:

alias ..='cd ..'
alias amazonbackup='s3backup'
alias apt-get='sudo apt-get'
...

By default alias command shows a list of aliases that are defined for the current user.

Task: Define / create an alias (bash syntax)

To create the alias use the following syntax:

alias name=value
 alias name='command'
 alias name='command arg1 arg2'
 alias name='/path/to/script'
 alias name='/path/to/script.pl arg1'

In this example, create the alias c for the commonly used clear command, which clears the screen, by typing the following command and then pressing the ENTER key:

alias c='clear'

Then, to clear the screen, instead of typing clear, you would only have to type the letter ‘c’ and press the [ENTER] key:

c

Task: Disable an alias temporarily (bash syntax)

An alias can be disabled temporarily using the following syntax:

# path/to/full/command
 /usr/bin/clear
# call alias with a backslash
 c

Task: Remove an alias (bash syntax)

You need to use the command called unalias to remove aliases. Its syntax is as follows:

unalias aliasname

In this example, remove the alias c which was created in an earlier example:

unalias c

You also need to delete the alias from the ~/.bashrc file using a text editor (see next section).

Task: Make aliases permanent (bash syntax)

The alias c remains in effect only during the current login session. Once you logs out or reboot the system the alias c will be gone. To avoid this problem, add alias to your ~/.bashrc file, enter:

vi ~/.bashrc

The alias c for the current user can be made permanent by entering the following line:

alias c='clear'

Save and close the file. System-wide aliases (i.e. aliases for all users) can be put in the /etc/bashrc file. Please note that the alias command is built into a various shells including ksh, tcsh/csh, ash, bash and others.

A note about privileged access

You can add code as follows in ~/.bashrc:

# if user is not root, pass all commands via sudo
 if [ $UID -ne 0 ]; then
 alias reboot='sudo reboot'
 alias update='sudo apt-get upgrade'
 fi

A note about os specific aliases

You can add code as follows in ~/.bashrc using the case statement:

# Get os name via uname
 _myos="$(uname)"

# add alias as per os using $_myos
 case $_myos in
 Linux) alias foo='/path/to/linux/bin/foo';;
 FreeBSD|OpenBSD) alias foo='/path/to/bsd/bin/foo' ;;
 SunOS) alias foo='/path/to/sunos/bin/foo' ;;
 *) ;;
 esac

30 uses for aliases

You can define various types aliases as follows to save time and increase productivity.

0: Control ls command output

The ls command lists directory contents and you can colorize the output:

# Use a long listing format #
 alias ll='ls -la'

# Show hidden files
 alias l.='ls -d .* --color=auto'
# Colorize the ls output
 alias ls='ls --color=auto'

1: Control cd command behavior

# get rid of command not found
 alias cd..='cd ..'
# a quick way to get out of current directory
 alias ..='cd ..'
 alias ...='cd ../../../'
 alias ....='cd ../../../../'
 alias .....='cd ../../../../'
 alias .4='cd ../../../../'
 alias .5='cd ../../../../..'

2: Control grep command output

grep command is a command-line utility for searching plain-text files for lines matching a regular expression:

# Colorize the grep command output for ease of use (good for log files)
 alias grep='grep --color=auto'
 alias egrep='egrep --color=auto'
 alias fgrep='fgrep --color=auto'

3: Start calculator with math support

alias bc='bc -l'

4: Generate sha1 digest

alias sha1='openssl sha1'

5: Create parent directories on demand

mkdir command is used to create a directory:

alias mkdir='mkdir -pv'

6: Colorize diff output

You can compare files line by line using diff and use a tool called colordiff to colorize diff output:

install colordiff package :)

 alias diff='colordiff'

7: Make mount command output pretty and human readable format

 alias mount='mount |column -t'

8: Command short cuts to save time

# handy short cuts
 alias h='history'
 alias j='jobs -l'

9: Create a new set of commands

 alias path='echo -e ${PATH//:/n}'
 alias now='date +"%T"'
 alias nowtime=now
 alias nowdate='date +"%d-%m-%Y"'

10: Set vim as default

 alias vi=vim
 alias svi='sudo vi'
 alias vis='vim "+set si"'
 alias edit='vim'

11: Control output of networking tool called ping

# Stop after sending count ECHO_REQUEST packets #
 alias ping='ping -c 5'
# Do not wait interval 1 second, go fast #
 alias fastping='ping -c 100 -s.2'

12: Show open ports

Use netstat command to quickly list all TCP/UDP port on the server:

alias ports=‘netstat -tulanp’


13: Wakeup sleeping servers

Wake-on-LAN (WOL) is an Ethernet networking standard that allows a server to be turned on by a network message. You can quickly wakeup nas devices and server using the following aliases:

# replace mac with your actual server mac address
 alias wakeupnas01='/usr/bin/wakeonlan 00:11:32:11:15:FC'
 alias wakeupnas02='/usr/bin/wakeonlan 00:11:32:11:15:FD'
 alias wakeupnas03='/usr/bin/wakeonlan 00:11:32:11:15:FE'

14: Control firewall (iptables) output

Netfilter is a host-based firewall for Linux operating systems. It is included as part of the Linux distribution and it is activated by default. This post list most common iptables solutions required by a new Linux user to secure his or her Linux operating system from intruders.

# shortcut for iptables and pass it via sudo
 alias ipt='sudo /sbin/iptables'
 
# display all rules #
 alias iptlist='sudo /sbin/iptables -L -n -v --line-numbers'
 alias iptlistin='sudo /sbin/iptables -L INPUT -n -v --line-numbers'
 alias iptlistout='sudo /sbin/iptables -L OUTPUT -n -v --line-numbers'
 alias iptlistfw='sudo /sbin/iptables -L FORWARD -n -v --line-numbers'
 alias firewall=iptlist

15: Debug web server / cdn problems with curl

# get web server headers 
 alias header='curl -I'

# find out if remote server supports gzip / mod_deflate or not 
 alias headerc='curl -I --compress'

16: Add safety nets

# do not delete / or prompt if deleting more than 3 files at a time 
 alias rm='rm -I --preserve-root'

# confirmation 
 alias mv='mv -i'
 alias cp='cp -i'
 alias ln='ln -i'
# Parenting changing perms on / 
 alias chown='chown --preserve-root'
 alias chmod='chmod --preserve-root'
 alias chgrp='chgrp --preserve-root'

17: Update Debian Linux server

apt-get command is used for installing packages over the internet (ftp or http). You can also upgrade all packages in a single operations:

# distro specific - Debian / Ubuntu and friends #
 # install with apt-get
 alias apt-get="sudo apt-get"
 alias updatey="sudo apt-get --yes"
 
# update on one command
 alias update='sudo apt-get update && sudo apt-get upgrade' 

18: Update RHEL / CentOS / Fedora Linux server

yum command is a package management tool for RHEL / CentOS / Fedora Linux and friends:

# distrp specifc RHEL/CentOS
 alias update='yum update'
 alias updatey='yum -y update'

19: Tune sudo and su

# become root #
 alias root='sudo -i'
 alias su='sudo -i'

20: Pass halt/reboot via sudo

shutdown command bring the Linux / Unix system down:

# reboot / halt / poweroff
 alias reboot='sudo /sbin/reboot'
 alias poweroff='sudo /sbin/poweroff'
 alias halt='sudo /sbin/halt'
 alias shutdown='sudo /sbin/shutdown'

21: Control web servers

# also pass it via sudo so whoever is admin can reload it without calling you
 alias nginxreload='sudo /usr/local/nginx/sbin/nginx -s reload'
 alias nginxtest='sudo /usr/local/nginx/sbin/nginx -t'
 alias lightyload='sudo /etc/init.d/lighttpd reload'
 alias lightytest='sudo /usr/sbin/lighttpd -f /etc/lighttpd/lighttpd.conf -t'
 alias httpdreload='sudo /usr/sbin/apachectl -k graceful'
 alias httpdtest='sudo /usr/sbin/apachectl -t && /usr/sbin/apachectl -t -D DUMP_VHOSTS'

22: Alias into our backup stuff

# Backup scripts
# if cron fails or if you want backup on demand just run these commands
# again pass it via sudo so whoever is in admin group can start the job

 alias backup='sudo /home/scripts/admin/scripts/backup/wrapper.backup.sh --type local --taget /raid1/backups'
 alias nasbackup='sudo /home/scripts/admin/scripts/backup/wrapper.backup.sh --type nas --target nas01'
 alias s3backup='sudo /home/scripts/admin/scripts/backup/wrapper.backup.sh --type nas --target nas01 --auth /home/scripts/admin/.authdata/amazon.keys'
 alias rsnapshothourly='sudo /home/scripts/admin/scripts/backup/wrapper.rsnapshot.sh --type remote --target nas03 --auth /home/scripts/admin/.authdata/ssh.keys --config /home/scripts/admin/scripts/backup/config/adsl.conf'
 alias rsnapshotdaily='sudo /home/scripts/admin/scripts/backup/wrapper.rsnapshot.sh --type remote --target nas03 --auth /home/scripts/admin/.authdata/ssh.keys --config /home/scripts/admin/scripts/backup/config/adsl.conf'
 alias rsnapshotweekly='sudo /home/scripts/admin/scripts/backup/wrapper.rsnapshot.sh --type remote --target nas03 --auth /home/scripts/admin/.authdata/ssh.keys --config /home/scripts/admin/scripts/backup/config/adsl.conf'
 alias rsnapshotmonthly='sudo /home/scripts/admin/scripts/backup/wrapper.rsnapshot.sh --type remote --target nas03 --auth /home/scripts/admin/.authdata/ssh.keys --config /home/scripts/admin/scripts/backup/config/adsl.conf'
 alias amazonbackup=s3backup

23: Desktop specific - play avi/mp3 files on demand

play video files in a current directory

cd ~/Download/movie-name playavi or vlc

 alias playavi='mplayer *.avi'
 alias vlc='vlc *.avi'

# play all music files from the current directory #
 alias playwave='for i in *.wav; do mplayer "$i"; done'
 alias playogg='for i in *.ogg; do mplayer "$i"; done'
 alias playmp3='for i in *.mp3; do mplayer "$i"; done'

# play files from nas devices #
 alias nplaywave='for i in /nas/multimedia/wave/*.wav; do mplayer "$i"; done'
 alias nplayogg='for i in /nas/multimedia/ogg/*.ogg; do mplayer "$i"; done'
 alias nplaymp3='for i in /nas/multimedia/mp3/*.mp3; do mplayer "$i"; done'

# shuffle mp3/ogg etc by default #
 alias music='mplayer --shuffle *'

vnstat is console-based network traffic monitor. dnstop is console tool to analyze DNS traffic. tcptrack and iftop commands displays information about TCP/UDP connections it sees on a network interface and display bandwidth usage on an interface by host respectively.

# All of our servers eth1 is connected to the Internets via vlan / router etc
 alias dnstop='dnstop -l 5 eth1'
 alias vnstat='vnstat -i eth1'
 alias iftop='iftop -i eth1'
 alias tcpdump='tcpdump -i eth1'
 alias ethtool='ethtool eth1'

# work on wlan0 by default 

Only useful for laptop as all servers are without wireless interface

alias iwconfig='iwconfig wlan0'

25: Get system memory, cpu usage, and gpu memory info quickly

# pass options to free
 alias meminfo='free -m -l -t'

# get top process eating memory
 alias psmem='ps auxf | sort -nr -k 4'
 alias psmem10='ps auxf | sort -nr -k 4 | head -10'

# get top process eating cpu
 alias pscpu='ps auxf | sort -nr -k 3'
 alias pscpu10='ps auxf | sort -nr -k 3 | head -10'

# Get server cpu info
 alias cpuinfo='lscpu'

# older system use /proc/cpuinfo
 alias cpuinfo='less /proc/cpuinfo' 

# get GPU ram on desktop / laptop##
 alias gpumeminfo='grep -i --color memory /var/log/Xorg.0.log'

26: Control Home Router

The curl command can be used to reboot Linksys routers.

# Reboot my home Linksys WAG160N / WAG54 / WAG320 / WAG120N Router / Gateway from *nix.
alias rebootlinksys="curl -u 'admin:my-super-password' 'http://192.168.1.2/setup.cgi?todo=reboot'"

# Reboot tomato based Asus NT16 wireless bridge
alias reboottomato="ssh [email protected] /sbin/reboot"
27 Resume wget by default

The GNU Wget is a free utility for non-interactive download of files from the Web. It supports HTTP, HTTPS, and FTP protocols, and it can resume downloads too:

# this one saved by butt so many times ##
 alias wget='wget -c'
28 Use different browser for testing website
# my default browser
 alias browser=chrome

# this one saved by butt so many times
 alias ff4='/opt/firefox4/firefox'
 alias ff13='/opt/firefox13/firefox'
 alias chrome='/opt/google/chrome/chrome'
 alias opera='/opt/opera/opera'

# default ff
 alias ff=ff13

29: A note about ssh alias

Do not create ssh alias, instead use ~/.ssh/config OpenSSH SSH client configuration files. It offers more option. An example:

Host server10 Hostname 1.2.3.4 IdentityFile ~/backups/.ssh/id_dsa user foobar Port 30000 ForwardX11Trusted yes TCPKeepAlive yes

You can now connect to peer1 using the following syntax: $ ssh server10

30: It’s your turn to share…

## set some other defaults
 alias df='df -H'
 alias du='du -ch'

# top is atop, just like vi is vim
 alias top='atop'

## nfsrestart - must be root

refresh nfs mount / cache etc for Apache

alias nfsrestart='sync && sleep 2 && /etc/init.d/httpd stop && umount netapp2:/exports/http && sleep 2 && mount -o rw,sync,rsize=32768,wsize=32768,intr,hard,proto=tcp,fsc natapp2:/exports /http/var/www/html && /etc/init.d/httpd start'

# Memcached server status
 alias mcdstats='/usr/bin/memcached-tool 10.10.27.11:11211 stats'
 alias mcdshow='/usr/bin/memcached-tool 10.10.27.11:11211 display'

# quickly flush out memcached server
 alias flushmcd='echo "flush_all" | nc 10.10.27.11 11211'

# Remove assets quickly from Akamai / Amazon cdn
 alias cdndel='/home/scripts/admin/cdn/purge_cdn_cache --profile akamai'
 alias amzcdndel='/home/scripts/admin/cdn/purge_cdn_cache --profile amazon'

# supply list of urls via file or stdin
 alias cdnmdel='/home/scripts/admin/cdn/purge_cdn_cache --profile akamai --stdin'
 alias amzcdnmdel='/home/scripts/admin/cdn/purge_cdn_cache --profile amazon --stdin'

Conclusion

This post summaries several types of uses for *nix bash aliases:

  1. Setting default options for a command (e.g. set eth0 as default option - alias ethtool=‘ethtool eth0’ ).
  2. Correcting typos (cd.. will act as cd .. via alias cd..=‘cd ..').
  3. Reducing the amount of typing.
  4. Setting the default path of a command that exists in several versions on a system (e.g. GNU/grep is located at /usr/local/bin/grep and Unix grep is located at /bin/grep. To use GNU grep use alias grep='/usr/local/bin/grep’ ).
  5. Adding the safety nets to Unix by making commands interactive by setting default options. (e.g. rm, mv, and other commands).
  6. Compatibility by creating commands for older operating systems such as MS-DOS or other Unix like operating systems (e.g. alias del=rm ).