|
Softpanorama |
May the source be with you, but remember the KISS principle ;-)
Softpanorama Search
|
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.
- /etc/profile -- system wide shell initialization script. Executed during login only for each user including root. In a large corporate environment it can serve as a substitute for local .profile files.
- .profile user customizable part of the profile for both Born shell and Korn Shell. Like /etc/profile $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.
- $ENV file (name is user selectable but usually .kshrc, .kshenv or .aliases). Executed upon each invocation of the shell. $ENV file is not unique to ksh, other shell also use this variable. 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,
not only when you login. For this reason, the typical thing you want to do in this script is set, or modify, shell options or aliases. You can set environment variables here, but it's probably redundant and inefficient because exported environment variables are propagated to the child processes from the login shell.
| .login files | -- Executed upon login |
| .cshrc files | -- Executed upon each invocation of the shell |
Contrary to popular urban myth .logout file is not executed for ksh users. You can make it execute by defining it as an alias for exit.
Other dot files include:
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.
- Dr. Nikolai Bezroukov
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:
- \!: The history number of the command
- \h: hostname
- $kernel_version: The output of the uname -r command from $kernel_version variable
- \$?: Status of the last command
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]
- \e[ - Indicates the beginning of color prompt
- x;ym - Indicates color code. Use the color code values mentioned below.
- \e[m - indicates the end of color 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:
- \e[40m
- \e[41m
- \e[42m
- \e[43m
- \e[44m
- \e[45m
- \e[46m
- \e[47m
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 setab [1-7] - Set a background color using ANSI escape
- tput setb [1-7] - Set a background color
- tput setaf [1-7] - Set a foreground color using ANSI escape
- tput setf [1-7] - Set a foreground color
tput Text Mode Capabilities:
- tput bold - Set bold mode
- tput dim - turn on half-bright mode
- tput smul - begin underline mode
- tput rmul - exit underline mode
- tput rev - Turn on reverse mode
- tput smso - Enter standout mode (bold on rxvt)
- tput rmso - Exit standout mode
- tput sgr0 - Turn off all attributes
Color Code for tput:
- 0 - Black
- 1 - Red
- 2 - Green
- 3 - Yellow
- 4 - Blue
- 5 - Magenta
- 6 - Cyan
- 7 - White
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 ##################
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
The PS1 promptIf 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.
#-----------------------------------------------#
# 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"
RTM06-11-2002, 11:32 AMHere 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.
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 1Note 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.htmlRecall 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 2The 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 3and 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 4are 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_userIn 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" 0This 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
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 ~/.bashrcYou can also create a ~/.bash_logout file that is executed whenever you log out.
UnixWorld Online Tutorial Article No. 018 -- Getting the Most From Your Shell -- good intro article
This is simply the text file .profile in your home directory. It runs immediately after /etc/profile when you first start a Born shell or Korn shell session (as well as bash session if .bash_profile is absent). It's not required, but it's highly recommended to have one. You can use this profile to:
export DISPLAY=pfuntnr:0
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
\d
\n
\s
$0 (the portion
following the final slash).
\w
\W
$PWD.
\u
\h
\#
\!
\nnn
nnn.
\$
#, otherwise $.
\\
\[
\]
Copyright © 1996-2009 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. Submit comments This document is an industrial compilation designed and created exclusively for educational use and is placed under the copyright of the Open Content License(OPL). Site uses AdSense so you need to be aware of Google privacy policy. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.
Disclaimer:
Last modified: August 15, 2009
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 !