Customize the bash shell environments
Customize the bash shell environments
Jump to navigationJump to search
← Bash variable existence check • Home • Recalling command history →
Strictly speaking there are two types of shell variables:
Local variables (shell variable) - Used by shell and or user scripts. All user created variables are local unless exported using the export command.
Environment variables - Used by shell or user but they are also passed onto other command. Environment variables are passed to subprocesses or subshells.
Contents
How do I configure and customize the Bash shell environment?
Your Bash shell can be configured using the following:
What should I put in shell starup files for customization?
A typically Linux or UNIX user do the following:
Setup a custom prompt.
Setup terminal settings depending on which terminal you're using.
Set the search path such as JAVA_HOME, and ORACLE_HOME.
Set environment variables as needed by programs.
Run commands that you want to run whenever you log in or log out.
How do I view local variables?
Use the set built-in command to view all variables:
set
Usually, all upper-case variables are set by bash. For example,
echo $SHELL echo $MAIL
How do I export local variables?
Use the export command:
export EDITOR=/usr/bin/vim
export DISPLAY environment variable and run xeyes
export DISPLAY=localhost:11.0 xeyes
Be careful when changing the shell variables. For a complete list of variables set by shell, read the man page for bash by typing the following command:
man bash
How do I view environment variables?
Use the env command to view all environment variables:
env
Sample outputs:
ORBIT_SOCKETDIR=/tmp/orbit-vivek SSH_AGENT_PID=4296 GPG_AGENT_INFO=/tmp/gpg-ElCDl5/S.gpg-agent:4297:1 TERM=xterm SHELL=/bin/bash XDG_SESSION_COOKIE=186611583e30fed08439ca0047067c9d-1255929792.297209-1700262470 GTK_RC_FILES=/etc/gtk/gtkrc:/home/vivek/.gtkrc-1.2-gnome2 WINDOWID=48252673 GTK_MODULES=canberra-gtk-module USER=vivek SSH_AUTH_SOCK=/tmp/keyring-s4fcR1/socket.ssh GNOME_KEYRING_SOCKET=/tmp/keyring-s4fcR1/socket SESSION_MANAGER=local/vivek-desktop:/tmp/.ICE-unix/4109 USERNAME=vivek DESKTOP_SESSION=gnome PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games GDM_XSERVER_LOCATION=local PWD=/home/vivek LANG=en_IN GDM_LANG=en_IN GDMSESSION=gnome SHLVL=1 HOME=/home/vivek GNOME_DESKTOP_SESSION_ID=this-is-deprecated LOGNAME=vivek DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-16XVNAMkFB,guid=0acb6a08e3992ccc7338726c4adbf7c3 XDG_DATA_DIRS=/usr/local/share/:/usr/share/:/usr/share/gdm/ WINDOWPATH=7 DISPLAY=:0.0 COLORTERM=gnome-terminal XAUTHORITY=/home/vivek/.Xauthority OLDPWD=/usr/share/man _=/usr/bin/env
Common Environment Variables
HOME - Your home directory path.
PATH - Set your executable search path.
PWD - Your current working directory.
How do I locate command?
The which command displays the pathnames of the files which would be executed in the current environment. It does this by searching the PATH for executable files matching the names of the arguments.
which command-name
Show fortune command path which print a random, hopefully interesting, adage on screen. Type the following command:
which fortune
Sample output:
/usr/games/fortune
Display your current PATH:
echo $PATH
Sample outputs:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
Customize your PATH variable and remove /usr/games from PATH:
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
Now, try searching fortune command path, enter:
which fortune
Try executing fortune command:
fortune
Sample outputs:
-bash: fortune: command not found
The fortune command could not be located because '/usr/games' is not included in the PATH environment variable. You can type full command path (/usr/games/fortune) or simply add /usr/games to PATH variable:
export PATH=$PATH:/usr/games fortune
Sample outputs:
Your lucky number has been disconnected.
whereis command
The whereis command is used to locate the binary, source, and manual page files for a command.
whereis command-name whereis ls
Sample outputs:
ls: /bin/ls /usr/share/man/man1/ls.1.gz
whatis command
The whatis command is used display a short description about command. whatis command searches the manual page names and displays the manual page descriptions for a command:
whatis command-name whatis date whatis ip whatis ifconfig whatis ping
Sample outputs:
date (1) - print or set the system date and time ifconfig (8) - configure a network interface ping (8) - send ICMP ECHO_REQUEST to network hosts
Recalling command history
Jump to navigationJump to search
← Customize the bash shell environments • Home • Path name expansion →
Bash keeps a command history in buffer or a default file called ~/.bash_history.
The history buffer can hold many commands.
Use history command to display a list of command you entered at a shell prompt. You can also repeat commands stored in history.
The history command displays the history list with line numbers.
By default history is enabled but can be disabled using set builtin command.
You can recall the basic command with arrow keys.
Contents
See list of executed commands
Type the following command
history
Sample outputs:
10 wget http://humdi.net/vnstat/vnstat-1.9.tar.gz 11 tar -zxvf vnstat-1.9.tar.gz 12 cd vnstat-1.9 13 ls 14 vi INSTALL 15 make 16 cd examples/ 17 ls 18 vi vnstat.cgi 19 cd .. 20 ls 21 cd cfg/ 22 ls 23 vi vnstat.conf 24 cd /t, 25 cd /tmp/ 26 yumdownloader --source vnstat 27 rpm -ivh vnstat-1.6-1.el5.src.rpm 28 cd -
Recall commands
Simply hit [Up] and [Down] arrow keys.
Interactively search history
Press [CTRL-r] from the shell prompt to search backwords through history buffer or file for a command:
(reverse-i-search)`rpm ': rpm -ql rhn-client-tools-0.4.20-9.el5
To repeat last command
Just type !! at a shell prompt:
date !!
To repeat last command started with ...
Recall the most recent command starting with vn
date vnstat ls ifconfig route -n !vn
To repeat a command by its number
Recall to command line number 13:
history !13
See history command help page for more detailed information about the events and usage:
man bash help history
This is what it prints:
history: history [-c] [-d offset] [n] or history -anrw [filename] or history -ps arg [arg...] Display or manipulate the history list.
Path name expansion
Jump to navigationJump to search
← Recalling command history • Home • Create and use aliases →
Bash shell support path name expansion using the following techniques. Let us see examples and syntax.
Contents
Curly braces
A curly braces ({..}) expands to create pattern and syntax is:
{ pattern1, pattern2, patternN } text{ pattern1, pattern2, patternN } text1{ pattern1, pattern2, patternN }text2 command something/{ pattern1, pattern2, patternN }
It will save command typing time.
Arbitrary strings may be generated.
Examples
Create a string pattern:
echo I like {tom,jerry}
Sample outputs:
I like tom jerry
A string is created, however this can be used to create unique file names:
echo file{1,2,3}.txt
Sample outputs:
file1.txt file2.txt file3.txt
OR
echo file{1..5}.txt
Sample outputs:
file1.txt file2.txt file3.txt file4.txt file5.txt
The filenames generated do not need to exist. You can also run a command for every pattern inside the braces. Usually, you can type the following to list three files:
ls -l /etc/resolv.conf /etc/hosts /etc/passwd
But, with curly braces:
ls /etc/{resolv.conf,hosts,passwd}
Sample outputs: To remove files called hello.sh, hello.py, hello.pl, and hello.c, enter:
rm -v hello.{sh,py,pl,c}
Another example:
D=/webroot mkdir -p $D/{dev,etc,bin,sbin,var,tmp}
Wildcards
Bash supports the following three simple wildcards:
***** - Matches any string, including the null string
? - Matches any single (one) character.
[...] - Matches any one of the enclosed characters.
Examples
To display all configuration (.conf) files stored in /etc directory, enter:
ls /etc/*.conf
To display all C project header files, enter:
ls *.h
To display all C project .c files, enter:
ls *.c
You can combine wildcards with curly braces:
ls *.{c,h}
Sample outputs:
f.c fo1.c fo1.h fo2.c fo2.h fo3.c fo3.h fo4.c fo4.h fo5.c fo5.h t.c
To list all png file (image1.png, image2.png...image7.png, imageX.png), enter:
ls image?.png
To list all file configuration file start with either letter a or b, enter:
ls /etc/[ab]*.conf
← Recalling command history • Home • Create and use aliases →
Navigation menu
Search
Tools
Printable version
Create and use aliases
Jump to navigationJump to search
← Path name expansion • Home • The tilde expansion →
An alias is nothing but shortcut to commands.
Use alias command to display list of all defined aliases.
Add user defined aliases to ~/.bashrc file.
Contents
Create and use aliases
Use the following syntax:
alias name='command' alias name='command arg1 arg2'
Examples
Create an aliase called c to clear the terminal screen, enter:
alias c='clear'
To clear the terminal, enter:
c
Create an aliase called d to display the system date and time, enter:
alias d='date' d
Sample outputs:
Tue Oct 20 01:38:59 IST 2009
How do I remove the alias?
Aliases are created and listed with the alias command, and removed with the unalias command. The syntax is:
unalias alias-name unalias c unalias c d
To list currently defined aliases, enter:
alias
alias c='clear' alias d='date'
If you need to unalise a command called d, enter:
unalias d alias
If the -a option is given, then remove all alias definitions, enter:
unalias -a alias
How do I permanently add aliases to my session?
If you want to add aliases for every user, place them either in /etc/bashrc or /etc/profile.d/useralias.sh file. Please note that you need to create /etc/profile.d/useralias.sh file.
Sample ~/.bashrc file
Example ~/.bashrc script:
make sure bc start with standard math library
alias bc='bc -l'
protect cp, mv, rm command with confirmation
alias cp='cp -i' alias mv='mv -i' alias rm='rm -i'
Make sure dnstop only shows eth1 stats
alias dnstop='dnstop -l 5 eth1'
Make grep pretty
alias grep='grep --color'
ls command shortcuts
alias l.='ls -d .* --color=tty' alias ll='ls -l --color=tty' alias ls='ls --color=tty'
Centos/RHEL server update
alias update='yum update' alias updatey='yum -y update'
vi is vim
alias vi='vim'
Make sure vnstat use eth1 by default
alias vnstat='vnstat -i eth1'
How do I ignore an alias?
Consider the following example:
alias ls='ls --color'
To ignore an alias called ls and run ls command, enter[1]:
\ls
OR
"ls"
Or just use the full path:
/bin/ls $(which ls)
See also
References
Changing bash prompt
Jump to navigationJump to search
← Using aliases • Home • Setting shell options →
Task: You need to customize your bash prompt by editing PS1 variable.
Display, your current prompt setting, enter:
echo $PS1
Sample outputs:
\u@\h:\w$
For testing purpose set PS1 as follows and notice the change:
PS1='your wish is my command : '
Sample outputs:
vivek@vivek-desktop:~$ PS1='your wish is my command : ' your wish is my command :
Contents
Customizing Prompt
Bash shell allows prompt strings to be customized by inserting a number of backslash-escaped special characters. Quoting from the bash man page:
\a
An ASCII bell character (07)
\d
The date in "Weekday Month Date" format (e.g., "Tue May 26")
\e
An ASCII escape character (033)
\h
The hostname up to the first .
\H
The hostname (FQDN)
\j
The number of jobs currently managed by the shell
\l
The basename of the shell’s terminal device name
Newline
Carriage return
\s
The name of the shell, the basename of $0 (the portion following the final slash)
The current time in 24-hour HH:MM:SS format
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 T
The release of bash, version + patch level (e.g., 2.00.0)
\w
The current working directory, with $HOME abbreviated with a tilde
\W
The basename of the current working directory, with $HOME abbreviated with a tilde
!
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
You can use above backslash-escaped sequence to display name of the host with current working directory:
PS1='\h \W $ '
Adding color to prompt
It is quite easy to add colors to your prompt. Set green color prompt for normal user account[1]:
export PS1='[\e[1;32m][\u@\h \W]$[\e[0m] '
And red color prompt for root user account:
export PS1='[\e[1;31m][\u@\h \W]$[\e[0m] '
How do I make prompt setting permanent?
Edit your ~/.bashrc or ~/.bash_profile
vi ~/.bashrc
Append your PS1 definition:
export PS1='[\e[1;32m][\u@\h \W]$[\e[0m] '
Save and close the file.
PROMPT_COMMAND variable
If PROMPT_COMMAND environment variable set, the value is executed as a command prior to issuing each primary prompt. In other words, the contents of this variable are executed as a regular Bash command just before Bash displays a prompt[2]:
PROMPT_COMMAND="echo Yahooo"
Sample outputs:
[vivek@vivek-desktop man]$ PROMPT_COMMAND="echo Yahooo" Yahooo [vivek@vivek-desktop man]$ date Tue Oct 20 23:50:01 IST 2009 Yahooo
Creating complex prompt
Edit ~/.bashrc file:
vi ~/.bashrc
Add the following two shell functions[3]
bash_prompt_command() { # How many characters of the $PWD should be kept local pwdmaxlen=25 # Indicate that there has been dir truncation local trunc_symbol=".." local dir=${PWD##/} pwdmaxlen=$(( ( pwdmaxlen < ${#dir} ) ? ${#dir} : pwdmaxlen )) NEW_PWD=${PWD/#$HOME/~} local pwdoffset=$(( ${#NEW_PWD} - pwdmaxlen )) if [ ${pwdoffset} -gt "0" ] then NEW_PWD=${NEW_PWD:$pwdoffset:$pwdmaxlen} NEW_PWD=${trunc_symbol}/${NEW_PWD#/} fi }
bash_prompt() { case $TERM in xterm*|rxvt*) local TITLEBAR='[\033]0;\u:${NEW_PWD}\007]' ;; *) local TITLEBAR="" ;; esac local NONE="[\033[0m]" # unsets color to term's fg color
}
init it by setting PROMPT_COMMAND
PROMPT_COMMAND=bash_prompt_command bash_prompt unset bash_prompt
References
↑ PROMPT_COMMAND from Bash prompt howto
↑ Color bash prompt code taken from the official Arch Linux wiki
External links
Setting shell options
Jump to navigationJump to search
← Changing bash prompt • Home • Setting system wide shell options →
The set and shopt command controls several values of variables controlling shell behavior.
Bash structured language constructs
Jump to navigationJump to search
← Chapter 4: Conditionals Execution (Decision Making) • Home • Test command →
You can use the if command to test a condition. For example, shell script may need to execute tar command only if a certain condition exists (such as backup only on Friday night).
If today is Friday execute tar command otherwise print an error message on screen.
.
Contents
More About Logic
So far, the script you've used followed sequential flow:
#!/bin/bash echo "Today is $(date)" echo "Current directory : $PWD" echo "What Users Are Doing:" w
Each command and/or statement is executed once, in order in above script.
With sequential flow scripts, you cannot write complex applications (intelligent Linux scripts).
However, with if command you will be able to selectively run certain commands (or part) of your script.
You can create a warning message and run script more interactively using if command to execute code based on a condition.
But What Is A Condition?
A condition is nothing but an expression that evaluates to a boolean value (true or false).
In other words condition can be either true or false.
A condition is used in shell script loops and if statements.
So, How Do I Make One?
A condition is mainly a comparison between two values. Open a shell prompt (console) and type the following command:
echo $(( 5 + 2 ))
Sample Output:
7
Addition is 7. But,
echo $(( 5 < 2 ))
Sample Output:
0
Answer is zero (0). Shell simple compared two number and returned result as true or false. Is 5 is less than 2? No. So 0 is returned. The Boolean (logical data) type is a primitive data type having one of two values
True
False
In shell:
0 value indicates false.
1 or non-zero value indicate true.
Examples
5 > 12
echo $(( 5 > 12 ))
Is 5 greater than 12?
No (false)
0
5 == 10
echo $(( 5 == 10 ))
Is 5 equal to 10?
No (false)
0
5 != 2
echo $(( 5 != 2 ))
5 is not equal to 2?
Yes (true)
1
1 < 2
echo $(( 1 < 2 ))
Is 1 less than 2?
Yes (true)
1
5 == 5
echo $(( 5 == 5 ))
Is 5 equal to 5?
Yes (true)
1
Now, it makes no sense to use echo command for comparisons. But, when you compare it with some value it becomes very useful. For example:
if [ file exists /etc/resolv.conf ] then make a copy else print an error on screen fi
Contents
List currently configured shell options
Type the following command:
set -o
Sample outputs:
allexport off braceexpand on emacs on errexit off errtrace off functrace off hashall on histexpand on history on ignoreeof off interactive-comments on keyword off monitor on noclobber off noexec off noglob off nolog off notify off nounset off onecmd off physical off pipefail off posix off privileged off verbose off vi off xtrace off
See set command for detailed explanation of each variable.
How do I set and unset shell variable options?
To set shell variable option use the following syntax:
set -o variableName
To unset shell variable option use the following syntax:
set +o variableName
Examples
Disable which is used to logout of a login shell (local or remote login session over ssh).
set -o ignoreeof
Now, try pressing [CTRL-d] Sample outputs:
Use "exit" to leave the shell.
Turn it off, enter:
set +o ignoreeof
shopt command
You can turn on or off the values of variables controlling optional behavior using the shopt command. To view a list of some of the currently configured option via shopt, enter:
shopt shopt -p
Sample outputs:
cdable_vars off cdspell off checkhash off checkwinsize on cmdhist on compat31 off dotglob off execfail off expand_aliases on extdebug off extglob off extquote on failglob off force_fignore on gnu_errfmt off histappend off histreedit off histverify off hostcomplete on huponexit off interactive_comments on lithist off login_shell off mailwarn off no_empty_cmd_completion off nocaseglob off nocasematch off nullglob off progcomp on promptvars on restricted_shell off shift_verbose off sourcepath on xpg_echo off
How do I enable (set) and disable (unset) each option?
To enable (set) each option, enter:
shopt -s optionName
To disable (unset) each option, enter:
shopt -u optionName
Examples
If cdspell option set, minor errors in the spelling of a directory name in a cd command will be corrected. The errors checked for are transposed characters, a missing character, and one character too many. If a correction is found, the corrected file name is printed, and the command proceeds. For example, type the command (note /etc directory spelling):
cd /etcc
Sample outputs:
bash: cd: /etcc: No such file or directory
Now, turn on cdspell option and try again the same cd command, enter:
shopt -s cdspell cd /etcc
Sample outputs:
/etc [vivek@vivek-desktop /etc]$
Customizing Bash environment with shopt and set
Edit your ~/.bashrc, enter:
vi ~/.bashrc
Add the following commands:
Correct dir spellings
shopt -q -s cdspell
Make sure display get updated when terminal window get resized
shopt -q -s checkwinsize
Turn on the extended pattern matching features
shopt -q -s extglob
Append rather than overwrite history on exit
shopt -s histappend
Make multi-line commandsline in history
shopt -q -s cmdhist
Get immediate notification of background job termination
set -o notify
Disable [CTRL-D] which is used to exit the shell
set -o ignoreeof
Disable core files
ulimit -S -c 0 > /dev/null 2>&1
How do I setup environment variables?
Simply add the settings to ~/.bashrc:
Store 5000 commands in history buffer
export HISTSIZE=5000
Store 5000 commands in history FILE
export HISTFILESIZE=5000
Avoid duplicates in hisotry
export HISTIGNORE='&:[ ]*'
Use less command as a pager
export PAGER=less
Set vim as default text editor
export EDITOR=vim export VISUAL=vim export SVN_EDITOR="$VISUAL"
Oracle database specific
export ORACLE_HOME=/usr/lib/oracle/xe/app/oracle/product/10.2.0/server export ORACLE_SID=XE export NLS_LANG=$($ORACLE_HOME/bin/nls_lang.sh)
Set JAVA_HOME
export JAVA_HOME=/usr/lib/jvm/java-6-sun/jre
Add ORACLE, JAVA and ~/bin bin to PATH
export PATH=$PATH:$ORACLE_HOME/bin:$HOME/bin:$JAVA_HOME/bin
Secure SSH login stuff using keychain
No need to input password again ever
/usr/bin/keychain $HOME/.ssh/id_dsa source $HOME/.keychain/$HOSTNAME-sh
Turn on Bash command completion
source /etc/bash_completion
MS-DOS / XP cmd like stuff
alias edit=$VISUAL alias copy='cp' alias cls='clear' alias del='rm' alias dir='ls' alias md='mkdir' alias move='mv' alias rd='rmdir' alias ren='mv' alias ipconfig='ifconfig'
Other Linux stuff
alias bc='bc -l' alias diff='diff -u'
get updates from RHN
alias update='yum -y update'
set eth1 as default
alias dnstop='dnstop -l 5 eth1' alias vnstat='vnstat -i eth1'
force colorful grep output
alias grep='grep --color'
ls stuff
alias l.='ls -d .* --color=tty' alias ll='ls -l --color=tty' alias ls='ls --color=tty'