Custom bash_profile for Advanced Shell Users

FREE THOUGHT · FREE SOFTWARE · FREE WORLD

Custom bash_profile for Advanced Shell Users

Looking for some advanced uses for the shell? Function examples? Advanced shell settings? Here is some of my best.

Want to get started without even having to read this page? Type the following in your shell.

curl -O http://z.askapache.com/askapache-bash-profile.txt && source askapache-bash-profile.txt

For those of you power users and server admins that use Bash, ksh, csh, vanilla sh, etc.., or if you are just passionate about shell scripting, because it allows you to get advanced tasks done fast and efficiently, not to mention automated automatically. I give you my .bash_profile file. You should edit it to fit your needs, (especially the exported vars like PATH, LDFLAGS, if you don’t understand something just comment it out) but it’s pretty universal because I work on alot of other people’s servers not to mention many different distros and platforms, and when I get hired to do some server work through a shell, I bring this script along for the ride.

askapache-bash_profile

askapache-bash-profile.txt

You can download the latest version: http://z.askapache.com/askapache-bash-profile.txt

The functions and variables below are the way bash sees them, using declare -f, and alias, to make it easier for you to read and understand them. The actual file at http://z.askapache.com/askapache-bash-profile.txt will always be the most updated version, as I use it personally. And it has the whole file the way I wrote it, meaning many extra notes and much simpler to follow. Enjoy!

#!/bin/bash
#
# To install the latest version
#
# curl -O http://z.askapache.com/askapache-bash-profile.txt && source askapache-bash-profile.txt
#
# To run automatically at login: In your ~/.bash_profile or similar login script do
# [[ -r path-to-askapache-bash-profile.txt ]] && source path-to-askapache-bash-profile.txt
#
 
AAPN='AskApache Bash Profile Script'
AAPV='5.6'
AAPT='2009-22-2009'
AAPS=`echo "$0" | sed -e 's,.*/,,'`
 
############################################################################################################################################################
# Copyright (C) 2009 www.AskApache.com
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
############################################################################################################################################################
 
# dont do anything for non-interactive shells
[[ -z "$PS1"  ]] && return
 
# bash defines the following built-in commands:
#   :, ., [, alias, bg, bind, break, builtin, case, cd, command, compgen, complete, continue, declare, dirs
#   disown, echo, enable, eval, exec, exit, export, fc, fg, getopts, hash, help, history, if, jobs, kill,
#   let, local, logout, popd, printf, pushd, pwd, read, readonly, return, set, shift, shopt, source, suspend
#   test, times, trap, type, typeset, ulimit, umask, unalias, unset, until, wait, while
 
#------------------------------------------------------------------------------------------------------------------------------------------------------------
# The first digit selects the set user ID (4) and set group ID (2) and sticky (1) attributes.
# The second digit selects permissions for the user who owns the file: read (4), write (2), and execute (1)
# The third selects permissions for other users in the file's group, with the same values
# The fourth for other users not in the file's group, with the same values.
# [see man chmod, help umask]
#------------------------------------------------------------------------------------------------------------------------------------------------------------
umask 0022
 
#------------------------------------------------------------------------------------------------------------------------------------------------------------
# Trapping Signals to Catch Errors
#------------------------------------------------------------------------------------------------------------------------------------------------------------
# 1      2      3       4      5       6       7      8      9       10      11      12      13      14      15      17      18      19      20      21
# SIGHUP SIGINT SIGQUIT SIGILL SIGTRAP SIGABRT SIGBUS SIGFPE SIGKILL SIGUSR1 SIGSEGV SIGUSR2 SIGPIPE SIGALRM SIGTERM SIGCHLD SIGCONT SIGSTOP SIGTSTP SIGTTIN
# [see man bash, man signal, help trap]
#------------------------------------------------------------------------------------------------------------------------------------------------------------
trap 'echo -e "\n\n\n!!! TERMINATED SIG: [$?] AT LINE:$LINENO AFTER $SECONDS SECONDS !!!\n"|tee -a `tty 2>/dev/null`;' 15
 
#------------------------------------------------------------------------------------------------------------------------------------------------------------
# Advanced Shell Limits
#------------------------------------------------------------------------------------------------------------------------------------------------------------
# -S      use the `soft' resource limit
# -H      use the `hard' resource limit
# -a      all current limits are reported
# -c      the maximum size of core files created
# -d      the maximum size of a process's data segment
# -f      the maximum size of files created by the shell
# -l      the maximum size a process may lock into memory
# -m      the maximum resident set size
# -n      the maximum number of open file descriptors
# -p      the pipe buffer size
# -s      the maximum stack size
# -t      the maximum amount of cpu time in seconds
# -u      the maximum number of user processes
# -v      the size of v
# [see man getrlimit, help ulimit]
#------------------------------------------------------------------------------------------------------------------------------------------------------------
ulimit -S -c 0 # Don't want any coredumps
 
#------------------------------------------------------------------------------------------------------------------------------------------------------------
# Advanced Shell (set)tings
#------------------------------------------------------------------------------------------------------------------------------------------------------------
# e [errexit] Exit immediately if a command exits with a non-zero status.
# B [braceexpand] The shell will perform brace expansion.
# h [hashall] Remember the location of commands as they
# f [noglob]      Disable file name generation (globbing).
# H [histexpand]  Enable ! style history substitution.
# v [verbose]     Print shell input lines as they are read.
# x [xtrace]      Print commands and their arguments as they are executed.
# n [noexec]      Read commands but do not execute them.
# [history] Enable command history
# [see man bash, help set]
#------------------------------------------------------------------------------------------------------------------------------------------------------------
set +C +f +H +v +x +n -b -h -i -m -B
 
#------------------------------------------------------------------------------------------------------------------------------------------------------------
# Advanced Shell (shopt)ions
#------------------------------------------------------------------------------------------------------------------------------------------------------------
# cdable_vars             an argument to the cd builtin command that is not a directory is assumed to be the name of a variable dir to change to.
# cdspell                 minor errors in the spelling of a directory component in a cd command will be corrected.
# checkhash               bash checks that a command found in the hash table exists before execute it.  If no longer exists, a path search is performed.
# checkwinsize            bash checks the window size after each command and, if necessary, updates the values of LINES and COLUMNS.
# cmdhist                 bash attempts to save all lines of a multiple-line command in the same history entry.  Allows re-editing of multi-line commands.
# dotglob                 bash includes filenames beginning with a `.' in the results of pathname expansion.
# execfail                a non-int shell will not exit if it cannot execute the file specified as an argument to the exec builtin command, like int sh.
# expand_aliases          aliases are expanded as described above under ALIASES.  This option is enabled by default for interactive shells.
# extglob                 the extended pattern matching features described above under Pathname Expansion are enabled.
# histappend              the history list is appended to the file named by the value of the HISTFILE variable when shell exits, no overwriting the file.
# hostcomplete            and readline is being used, bash will attempt to perform hostname completion when a word containing a @ is being completed
# huponexit               bash will send SIGHUP to all jobs when an interactive login shell exits.
# interactive_comments    allow a word beginning with # to cause that word and all remaining characters on that line to be ignored in an interactive shell
# lithist                 if cmdhist option is enabled, multi-line commands are saved to the history with embedded newlines rather than using semicolon
# login_shell             shell sets this option if it is started as a login shell (see INVOCATION above).  The value may not be changed.
# mailwarn                file that bash is checking for mail has been accessed since the last checked, ``The mail in mailfile has been read'' is displayed.
# no_empty_cmd_completion bash will not attempt to search the PATH for possible completions when completion is attempted on an empty line.
# nocaseglob              bash matches filenames in a case-insensitive fashion when performing pathname expansion (see Pathname Expansion above).
# nullglob                bash allows patterns which match no files (see Pathname Expansion above) to expand to a null string, rather than themselves.
# progcomp                the programmable completion facilities (see Programmable Completion above) are enabled.  This option is enabled by default.
# promptvars              prompt strings undergo variable and parameter expansion after being expanded as described in PROMPTING above.
# shift_verbose           the shift builtin prints an error message when the shift count exceeds the number of positional parameters.
# sourcepath              the source (.) builtin uses the value of PATH to find the directory containing the file supplied as an argument.
# xpg_echo                the echo builtin expands backslash-escape sequences by default.
# [see man bash, help shopt]
#------------------------------------------------------------------------------------------------------------------------------------------------------------
shopt -s histappend cmdhist extglob no_empty_cmd_completion checkwinsize progcomp sourcepath cdspell cdable_vars checkhash histreedit histverify
shopt -u mailwarn; unset MAILCHECK # dont notify for new mail
 
#----------------------------
# CUSTOM SETTING VARIABLES
#----------------------------
 
# quicker, cleaner ref
export N6=/dev/null
 
# if a program exists in path
function have()
{ unset -v have; PATH=$PATH:/sbin:/usr/sbin:/usr/local/sbin; type $1 &>/$N6 && have="yes"; }
 
[[ -z ${USER:=""} ]] && export USER=`whoami 2>$N6 || id -un 2>$N6 || logname 2>$N6`
[[ -z ${HOME:=""} ]] && export HOME=$(command pwd -L)
 
export HOME=${HOME:-~};
export SHELL=${SHELL:-/bin/bash}
have tty && export SSHTTY=`tty 2>$N6`
 
export TZ='America/Indianapolis'
[[ -z "$HOST" ]] && export HOST=`hostname 2>$N6||uname -n 2>$N6`
 
# DEFINATELY EDIT THIS STUFF, is pretty good at setting path
#JAVA_HOME=/usr/local/jdk
#P=${PATH}:$HOME/bin:$HOME/sbin:/bin:/etc:/sbin:/usr/local/bin:/usr/sbin:/usr/X11R6/bin:/usr/bin:/usr/bin/mh:/usr/libexec:/etc/X11:/etc/X11/xinit:$HOME/.gem/ruby/1.8/bin
#P=${P}:/usr/local/dh/apache/template/bin:/usr/local/dh/apache2/template/bin:/usr/local/dh/apache2/template/build:/usr/local/dh/apache2/template/sbin
#P=${P}:/usr/local/dh/bin:/usr/local/dh/java/bin:/usr/local/dh/java/jre/bin:/usr/local/php5/bin:.
#PATH=$P
GP=; for p in ${PATH//:/ }; do [[ -d $p && -x $p ]] && [[ "${GP}s" == s ]] && GP=$p || GP=${GP}:$p; done; export PATH=$GP
 
#----------------------------
# LIBS / COMPILES - EDIT
#----------------------------
#LDFLAGS="-L${HOME}/lib -L/lib -L/usr/lib -L/usr/lib/libc5-compat -L/lib/libc5-compat -L/usr/i486-linuxlibc1/lib -L/usr/X11R6/lib"; LD_LIBRARY_PATH=$HOME/lib; CPPFLAGS="-I${HOME}/include"
#export LDFLAGS LD_LIBRARY_PATH CPPFLAGS
 
#----------------------------
# MAIL, PROGRAMS, EDITOR
#----------------------------
have nano && export EDITOR="`type -P nano`" && export VISUAL=$EDITOR
have lynx && export BROWSER="`type -P lynx`"
 
#alias man='man -H'
#[[ -r $HOME/.lynx/lynx.cfg ]] && export LYNX_CFG=$HOME/.lynx/lynx.cfg
#[[ -r $HOME/var/locatedb ]] && export LOCATE_PATH=$HOME/var/locatedb
 
alias more='less'
export PAGER=less
export LESSCHARSET='latin1'
have lesspipe && export LESSOPEN='|/usr/bin/lesspipe %s 2>&-' && export LESS='-i -N -w  -z-4 -g -e -M -X -F -R -P%t?f%f :stdin .?pb%pb\%:?lbLine %lb:?bbByte %bb:-...'
 
#------------------------------------------------------------------------------------------------------------------------------------------------------------
# PROMPT
#------------------------------------------------------------------------------------------------------------------------------------------------------------
# \a     an ASCII bell character (07)
# \d     the date in "Weekday Month Date" format (e.g., "Tue May 26")
# \D{format}  the format is passed to strftime(3) and the result is inserted into the prompt string;
# \e     an ASCII escape character (033)
# \h     the hostname up to the first `.'
# \H     the hostname
# \j     the number of jobs currently managed by the shell
# \l     the basename of the shell's terminal device name
# \n     newline
# \r     carriage return
# \s     the name of the shell, the basename of $0 (the portion following the final slash)
# \t     the current time in 24-hour HH:MM:SS format
# \T     the current time in 12-hour HH:MM:SS format
# \@     the current time in 12-hour am/pm format
# \A     the current time in 24-hour HH:MM format
# \u     the username of the current user
# \v     the version of bash (e.g., 2.00)
# \V     the release of bash, version + patchelvel (e.g., 2.00.0)
# \w     the current working directory
# \W     the basename of the current working directory
# \!     the history number of this command
# \#     the command number of this command
# \$     if the effective UID is 0, a #, otherwise a $
# \nnn   the character corresponding to the octal number nnn
# \\     a backslash
# \[     begin a sequence of non-printing characters, which could be used to embed a terminal control sequence into the prompt
# \]     end a sequence of non-printing characters
#------------------------------------------------------------------------------------------------------------------------------------------------------------
 
case ${TERM:-dummy} in linux*|con80*|con132*|console|xterm*|vt*|screen*|putty|Eterm|dtterm|ansi|rxvt|gnome*|*color*)COLORTERM=yes; ;; *) COLORTERM=no; ;; esac; export COLORTERM
PS1="\n[`date +%m/%d`][\u@\h][\w]($SHLVL:\!)\n$ "; X=;R=;
[[ "$COLORTERM" == yes ]] && X='\033[1;37m' && R='\033[0;00m' && PS1="\n[`date +%m/%d`]\e[1;37m[\e[0;32m\u\e[0;35m@\e[0;32m\h\e[1;37m]\e[1;37m[\e[0;31m\w\e[1;37m]($SHLVL:\!)\n\[${X}\]\$ "
export PS1 R X
 
# If set, the value is executed as a command prior to issuing each primary prompt.
have tty && export SSHTTY=$(tty 2>$N6);
[[ -z "$SSHTTY" ]] || export PROMPT_COMMAND='echo -ne "\033]0;$USER:`id -gn 2>$N6`@$HOSTNAME `tty 2>$N6`  [`uptime 2>$N6|sed -e "s/.*: \([^,]*\).*/\1/" -e "s/ //g"` / `command ps aux|wc -l`]  `command w|wc -l` users \007"'
unset PROMPT_COMMAND
 
# used by functions below
export RJ=0;
declare -a CC;
export L1=$(seq -s_ 1 75|tr -d [0-9]);
export L2=$(echo $L1|tr '_' ' ')
 
#---------------
# ls aliases
#---------------
C=' --color=auto'
alias la="command ls -Al${C}"      # show hidden files
alias lx="command ls -lAXB${C}"    # sort by extension
alias lk="command ls -lASr${C}"    # sort by size
alias lc="command ls -lAcr${C}"    # sort by change time
alias lu="command ls -lAur${C}"    # sort by access time
alias lr="command ls -lAR${C}"     # recursive ls
alias lt="command ls -lAtr${C}"    # sort by date
alias lll="stat -c %a\ %N\ %G\ %U \$PWD/*|sort"
 
#---------------
# safety aliases
#---------------
alias chmod='command chmod -c'
alias mkdir='command mkdir -pv'
alias rm='command rm -v'
alias cp='command cp -v'
alias mv='command mv -v'
 
#---------------
# func aliases
#---------------
alias who='command who -ar -pld'
alias which='command type -path'
have tree || alias tree='command -lsFR'
have tree && alias tree='command tree -Csuflapi'
alias top='top -c'
alias vim='command vim --noplugin'
alias du='command du -kh'
alias df='command df -kTh'
[[ $UNAME != Linux ]] && have gsed && alias sed=gsed
#alias php='php -d display_errors=true'
#alias man='man -H'
#alias ldconfig="ldconfig -v -f ${HOME}/etc/ld.so.conf -C ${HOME}/etc/ld.so.cache"
alias path='echo -e ${PATH//:/\\n}'
 
alias pp='command ps -HAcl -F S -A f'
alias p='command ps -HAcl -F S -A f|uniq -w3'
alias ps2='command ps -H'
alias ps1='command ps -lFA'
 
alias df1='command df -iTa'
alias n="${EDITOR}"3
alias inice='ionice -c3 -n7 nice'
alias vdir="ls --format=long"
alias dir="ls --format=vertical"
alias killphp='pkill -9 -f php.cgi\|php5.cgi\|php-cgi\|php\|php4.cgi;pkill -13 -f php.cgi\|php5.cgi\|php-cgi\|php\|php4.cgi'
alias dsiz='du -sk * | sort -n --'
alias lessc='ccze -A |/usr/bin/less -R'
alias h='history'
alias j='jobs -l'
alias ..='cd ..'
alias wtf='watch -n 1 w -hs'
 
# spelling typos
alias kk='ll'
alias xs='cd'
alias vf='cd'
alias moer='more'
alias moew='more'
 
#------------------------------------------------------------------------------------------------------------------------------------------------------------
# history setup
#------------------------------------------------------------------------------------------------------------------------------------------------------------
# HISTCONTROL
#    If  set  to a value of ignorespace, lines which begin with a space character are not entered on the history list.
#    If set to a value of ignoredups, lines matching the last history line are not entered.  A value of ignoreboth combines the two options.
#    If unset, or if set to any other value than those above, all lines read by the parser are saved on the history list, subject to the value of HISTIGNORE.
# HISTFILE
#    The name of the file in which command history is saved (see HISTORY below).  The default value is ~/.bash_history.  If unset, the command history is not saved when an interactive shell exits.
# HISTFILESIZE
#    The  maximum number of lines contained in the history file.  When this variable is assigned a value, the history file is truncated, if necessary, to contain no more than that number of lines.
#    The default value is 500.  The history file is also trun-cated to this size after writing it when an interactive shell exits.
# HISTIGNORE
#    A colon-separated list of patterns used to decide which command lines should be saved on the history list.  Each pattern is anchored at the beginning of the line and must match the complete line (no implicit `*' is appended).
#    Each pattern is  tested against  the  line  after  the  checks  specified  by HISTCONTROL are applied.  In addition to the normal shell pattern matching characters, `&' matches the previous history line.
#    `&' may be escaped using a backslash; the backslash is removed before attempting a match.  The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTIGNORE.
# HISTSIZE
#    The number of commands to remember in the command history (see HISTORY below).  The default value is 500.
#
HISTMASTER=;HISTCONTROL=;HISTIGNORE=;HISTSIZE=;HISTFILESIZE=;HISTFILE=;HISTTIMEFORMAT=;
function asetup_history()
{
  HISTMASTER=${HISTMASTER:-$HOME/backups/.history/combined.log}
  HISTCONTROL=${HISTCONTROL:-'ignoreboth'}
  HISTTIMEFORMAT="%H:%M > "
  HISTIGNORE=${HISTIGNORE:-'clear:ll:ls:./_sbackup.sh:./_logview.sh:ps:updatedb:top'}
  HISTSIZE=${HISTSIZE:-5000000}
  HISTFILESIZE=${HISTFILESIZE:-5000000}
  HISTFILE=${HISTFILE:-$HOME/.bash_history}
  export HISTMASTER HISTCONTROL HISTIGNORE HISTSIZE HISTFILESIZE HISTFILE HISTTIMEFORMAT
}
 
function h1()
{ cat $HISTFILE $HISTMASTER | command grep $1 | sort | uniq | command grep --color=always $1; }
 
function h2()
{ cat $HISTFILE $HISTMASTER | command grep $1 | sort | uniq; }
 
#------------------------------------------------------------------------------------------------------------------------------------------------------------
# personalized colors
#------------------------------------------------------------------------------------------------------------------------------------------------------------
# Attribute codes:        00=none 01=bold 04=underscore 05=blink 07=reverse 08=concealed
# Text color codes:       30=black 31=red 32=green 33=yellow 34=blue 35=magenta 36=cyan 37=white
# Background color codes: 40=black 41=red 42=green 43=yellow 44=blue 45=magenta 46=cyan 47=white
# NORMAL 00       # global default, although everything should be something.
# FILE 00         # normal file
# DIR 01;34       # directory
# LINK 01;36      # symbolic link.
# FIFO 40;33      # pipe
# SOCK 01;35      # socket
# DOOR 01;35      # door
# BLK 40;33;01    # block device driver
# CHR 40;33;01    # character device driver
# ORPHAN 40;31;01 # symlink to nonexistent file
# EXEC 01;32      # executables
LS_COLORS=;LS_OPTIONS=;
function asetup_colors(){
 local L; eval "`dircolors -b`";
 [[ "$COLORTERM" == no ]] && return
 export LS_COLORS
 unset LS_OPTIONS
}
 
function ascript_title(){
  clear; echo; echo; lin 0;
  echo -e "| ${CC[2]}             ___       __    ___                 __                     ${CC[0]} |"
  echo -e "| ${CC[2]}            / _ | ___ / /__ / _ | ___  ___ _____/ /  ___                ${CC[0]} |"
  echo -e "| ${CC[9]}           / __ |(_-</  '_// __ |/ _ \/ _ \`/ __/ _ \/ -_)               ${CC[0]} |"
  echo -e "| ${CC[9]}          /_/ |_/___/_/\_\/_/ |_/ .__/\_,_/\__/_//_/\__/                ${CC[0]} |"
  echo -e "| ${CC[9]}                               /_/                                      ${CC[0]} |";
  lin 1; lin 2 "${1:-$AAPN}"; lin 2 "Version ${2:-$AAPV}"; lin 2 "Build: ${3:-$AAPT}"; lin 3;sleep 2;
}
 
###########################################################################--=--=--=--=--=--=--=--=--=--=--#
###
### FUNCTIONS
###
###########################################################################==-==-==-==-==-==-==-==-==-==-==#
 
#export SMSO=$(tput smso &>$N6);export RMSO=$(tput rmso &>$N6);
#find . -type f -iname '*htaccess*' -print0 | xargs -0 grep -sn -i "THE_REQUEST" | sed "s/THE_REQUEST/${SMSO}\0$RMSO}/gI"
 
function repeat()
{ local i max=$1; shift; for ((i=1; i <= max ; i++)); do eval "$@"; done; }
 
function cuttail()
{ sed -n -e :a -e "1,${2:-10}!{P;N;D;};N;ba" $1; }
 
function quote()
{ echo \'${1//\'/\'\\\'\'}\'; }
 
function dequote()
{ eval echo "$1"; }
 
function get_pids_on_system()
{ command ps axo pid|sed 1d; }
 
function get_pgids_on_system()
{ command ps axo pgid|sed 1d; }
 
function get_users_on_system()
{ have getent &>$N6 && getent passwd|awk -F: '{print $1}' && return; awk 'BEGIN {FS=":"} {print $1}' /etc/passwd; }
 
function get_groups_on_system()
{ have getent &>$N6 && getent group|awk -F: '{print $1}' && return; awk 'BEGIN {FS=":"} {print $1}' /etc/group; }
 
function get_inet_interface_ips()
{ have ip && /bin/ip -o -f inet addr|sed -e '/inet 10./d' -e 's/\/24//g' |awk '{print $4}'|sed -e "s/\\n//g" -e '/.*\.0$/d'; }
 
function personalized_wget()
{
 exec 6>&1 ; exec > ${1:-$HOME/.wgetrc}
 echo 'header = Accept-Language: en-us,en;q=0.5'
 echo 'header = Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'
 echo 'header = Accept-Encoding: gzip,deflate'
 echo 'header = Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7'
 echo 'header = Keep-Alive: 300'
 echo 'user_agent = Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6'
 echo 'referer = http://www.google.com'
 echo 'robots = off'
 exec 1>&6 6>&-
}
 
function mkdir()
{
 local e=0;
 for f in ${1+"$@"};do
 set fnord `echo ":$f"|sed -e 's/^:\//%/' -e 's/^://' -e 's/\// /g' -e 's/^%/\//'`;shift;pp=;for d in ${1+"$@"};do pp="$pp$d";
 case "$pp" in -*)pp=./$pp; ;; ?:)pp="$pp/";continue ;; esac; [[ ! -d "$pp" ]] && mkdir -v "$pp"||e=$?; pp="$pp/"; done;
 done; return  $e
}
 
function clean_exit()
{ lin 0;lin 1;lin 2 "COMPLETED SUCCESSFULLY";lin 1;lin 3; }
 
function dirty_exit()
{ echo "See ya..";sleep 1;exit; }
 
function set_window_title()
{ echo -n -e "\033]0;$*\007"; }
 
function pd()
{ echo -e  "\n ${CC[15]} ${1:-DONE} $R\n\n" >$SSHTTY; }
 
function cont()
{ local ans; echo -en "\n ${CC[15]}[ ${1:-Press any key to continue} ]$R\n"; read -n 1 ans; }
 
function do_sleep ()
{ echo -en "${CC[6]}${3:-.}" >$SSHTTY;while [[ -d /proc/$RJ ]];do sleep ${2:-3};echo -en "${3:-.}" >$SSHTTY;done;echo -e "${CC[0]}" >$SSHTTY&&sleep 1&&pd; }
 
function pwd()
{ command pwd -LP "$@"; }
 
function kill_jobs(){
 for i in `jobs -p`; do kill -9 $i; done; }
 
function beep_alarm()
{ local i; for i in `seq 0 ${1:-5}`;do echo -en "\a" && sleep 1; done; }
 
function lin()
{ case ${1:-1} in 0)echo -e "\n$R $L1"; ;; 1)echo -e "|$L2|"; ;; 2)echo -en "${R}|${CC[34]}";echo -en "${2:-1}"|sed -e :a -e 's/^.\{1,72\}$/ & /;ta' -e "s/\(.*\)/\1/";echo -e "${R} |${R}" ;; 3)echo -e "$R $L1$R$X\n\n"; ;; esac; }
 
function mp3info()
{ ls *.mp3 |xargs -ix 2>&1 ffmpeg -i x|grep -v "^Must" |grep -v "built\|libavutil\|libavcodec\|configuration\|FFmpeg\|libavformat"; }
 
function tailit()
{ clear;echo "p e a ma md all | FILENAME"; sh ${HOME}/scripts/logview.sh "${2:-askapache.com}" "${1:-all}"; }
 
function pm()
{ local S I=${1:-3};S=$SSHTTY;echo -en "$R\n";case ${2:-0} in 0)echo -en "${CC[6]}==> $X$I$R" >$S; ;; 3)echo -e "\n\n${CC[4]}:: $X$I$R\n" >$S; ;; esac; }
 
function yes_no()
{ local a YN=65; echo -en "${1:-Answer} [y/n] "; read -n 1 a; case $a in [yY]) YN=0; ;; esac; return $YN; }
 
function l()
{ command ls -AhFp --color=auto "$@"; }
 
function la()
{ du *|awk '{print $2,$1}'|sort -n|tr ' ' "\t"; }
 
function ll()
{ command ls -lABls1c --color=auto "$@"; }
 
function stat1()
{ local D=${1:-$PWD/*}; stat -c %a\ %A\ \ A\ %x\ \ M\ %y\ \ C\ %z\ \ %N ${D} |sed -e 's/ [0-9:]\{8\}\.[0-9]\{9\} -[0-9]\+//g' |tr  -d "\`\'"|sort -r; }
 
function stat2()
{ local D=${1:-$PWD/*}; stat -c %a\ %A\ \ A\ %x\ \ M\ %y\ \ C\ %z\ \ %N ${D} |sed -e 's/\.[0-9]\{9\} -[0-9]\+//g'|tr  -d "\`\'"|sort -r; }
 
#--=--=--=--=--=--=--=--=--=--=--#
# processes
#==-==-==-==-==-==-==-==-==-==-==#
function psu()
{ command ps -Hcl -F S f -u ${1:-$USER}; }
 
function ps()
{ [[ -z "$1" ]] && command ps -Hacl -F S -A f && return; command ps "$@"; }
 
function make_nice()
{ have nice || return; pm "Making Nice $$"; pm 0 0; command renice ${1:-19} -p $$; pd; }
 
function make_ionice()
{ have ionice || return; pm "Making IONice $$"; pm 0 0; command ionice -c${1:-3} -n7 -p $$; pd; }
 
function dump_ps_environment()
{ command ps aux | grep ${USER:0:3} | awk '{print $2}' | xargs -t -ipid cat /proc/pid/environ; }
 
function procinfo1()
{ PI=($(strace -s1 procinfo -a 2>&1|sed -e '/^op/!d' -e '/pro/!d' -e '/= -1/d'|sed -e 's%o.*"/proc/\(.*\)".*% \1%g')); for i in ${PI[*]}; do echo -e "\n---===[  /proc/$i  ]\n" && cat /proc/$i && echo -e "\n\n"; done; }
 
function pss(){
  local U PPS PL PX PXX UUS=( $(command ps uax|awk '{print $1}'|command tail -n +2|sort|uniq) ); UL=$((${#UUS[@]} - 1))
  exec 6>&1; exec > ~/proc.$$
  ps aux | grep ${USER:0:3} | awk '{print $2}' | xargs -t -ipid cat /proc/pid/environ
  for UX in $(seq 0 1 $UUS); do U=${UUS[$UX]}; PPS=( $(pgrep -u ${U}) ); PL=$((${#PPS[@]} - 1));
   for PX in $(seq 0 1 $PL); do PXX=${PPS[$PX]};echo -e "\n\n\n----- PROCESS ID: ${PXX} -----\n\n";cat /proc/${PXX}/cmdline 2>$N6 || echo;echo -e "\n\n"; command tree -Csuflapi /proc/Q/${PXX};done
  done
  exec 1>&6 6>&-; cat ~/proc.$$ | more
}
 
function ashow_motd()
{ [[ -r /etc/motd ]] && echo -e "\n\n${CC[2]}`head -n 7 /etc/motd | tail -n 6`${R}\n"; }
 
function ashow_calendar()
{ [[ -d /usr/share/calendar/ ]] && echo -en "\n${CC[5]}" && ( sed = $(echo /usr/share/calendar/calendar*) | sed -n "/$(date +%m\\/%d\\\|%b\*\ %d)/p" ) && echo -en "${R}"; }
 
function ashow_fortune()
{ [[ -x /usr/games/fortune ]] && echo -en "\n${CC[6]}" && /usr/games/fortune -s && echo -en "${R}"; }
 
function askapache()
{
  ascript_title
  ashow_motd
 
  have who && pm "Users" && pm "Logged In" 3 &&  command who -ar -pld
  pm "Current Limits" 3;command ulimit -a
 
  pm "Machine stats";
  have uptime && pm "uptime" 3 && command uptime
  [[ -d /proc ]] && [[ -f /proc/meminfo ]] && cat /proc/meminfo
  have who && pm "Users" 3 && command who
 
  pm "Networking"
  have ip && pm "interfaces" 3 && ip -o addr|sed -e 's/ \{1,\}/\t/g'
  [[ -r /proc/net/sockstat ]] && pm "Sockets" 3 && head -n 2 /proc/net/sockstat
  have ss && pm "Networking Stats" 3 && ss -s
  have netstat && pm "Routing Information" 3 && netstat -r
 
  pm "Disk"
  pm "Mounts" 3; command df -hai
  #[[ -d /sys/block/ ]] && pm "IO Scheduling" 3; for d in /sys/block/[a-z][a-z][a-z]*/queue/*; do [[ -d $d ]] && tree $d; echo "$d => $(cat $d)";done
  have iostat && pm "I/O on Disks" && iostat -p ALL
 
  pm "Processes";
  pm "process tree" 3;  command ps -HAcl -F S -A f | uniq -w3
  have procinfo && pm "procinfo" 3 && procinfo|head -n 13|tail -n 11
}
 
asetup_colors
asetup_history
askapache
 

«
»

Skip to Comments

Add Your Opinion

Reader Comments

  1. larsx2 ~

    Amazing! My bash_profile looked so skinny.. thanks for the share. (And truly it is bash that is the heart of evrything on askapache)

  2. Wojtek ~

    The script looks great but for some reason I’m getting:
    # ./askapache-bash-profile.sh
    -bash: ./askapache-bash-profile.sh: /bin/bash

    : bad interpreter: No such file or directory

    I do have bash :) and /bin/bash do exists. Any idea why is this happening?

    # dos2unix -dv askapache-bash-profile.sh


It's very simple - you read the protocol and write the code. -Bill Joy

HTML | DCMI | GRDDL | XOXO | XDMP | XFN | DOM | XML | XHTML 1.1 Strict | CSS 2.1 | W3C | TLDP | WAI | DISA | ICSI | GIAC | SANS RR | GHOST | DEFCON | NIST | DHS CYBER | NIST

↑ TOPExcept where otherwise noted, content on this site is licensed under a Creative Commons Attribution 3.0 License, just credit with a link.
This site is not supported or endorsed by The Apache Software Foundation (ASF). All software and documentation produced by The ASF is licensed. "Apache" is a trademark of The ASF. HTTPD based on NCSA HTTPd

Site Map | Contact Webmaster | Email AskApache | Glossary | License and Disclaimer | Terms of Service