• •
Strictly speaking there are two types of shell variables:
(shell variable) - Used by shell and or user scripts. All user created variables are local unless exported using the .
- Used by shell or user but they are also passed onto other command. Environment variables are passed to subprocesses or subshells.
Your Bash shell can be configured using the following:
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.
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
export EDITOR=/usr/bin/vim
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
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
HOME - Your home directory path.
PATH - Set your executable search path.
PWD - Your current working directory.
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-name whereis ls
Sample outputs:
ls: /bin/ls /usr/share/man/man1/ls.1.gz
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
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.
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 -
Simply hit [Up] and [Down] arrow keys.
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
Just type !! at a shell prompt:
date !!
Recall the most recent command starting with vn
date vnstat ls ifconfig route -n !vn
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.
Bash shell support path name expansion using the following techniques. Let us see examples and syntax.
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.
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}
***** - Matches any string, including the null string
? - Matches any single (one) character.
[...] - Matches any one of the enclosed characters.
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
Printable version
An alias is nothing but shortcut to commands.
Use the following syntax:
alias name='command' alias name='command arg1 arg2'
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
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
Sample ~/.bashrc file
alias bc='bc -l'
alias cp='cp -i' alias mv='mv -i' alias rm='rm -i'
alias dnstop='dnstop -l 5 eth1'
alias grep='grep --color'
alias l.='ls -d .* --color=tty' alias ll='ls -l --color=tty' alias ls='ls --color=tty'
alias update='yum update' alias updatey='yum -y update'
alias vi='vim'
alias vnstat='vnstat -i eth1'
Consider the following example:
alias ls='ls --color'
\ls
OR
"ls"
Or just use the full path:
/bin/ls $(which ls)
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 :
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 $ '
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] '
vi ~/.bashrc
Append your PS1 definition:
export PS1='[\e[1;32m][\u@\h \W]$[\e[0m] '
Save and close the file.
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
vi ~/.bashrc
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
}
PROMPT_COMMAND=bash_prompt_command bash_prompt unset bash_prompt
The set and shopt command controls several values of variables controlling shell behavior.
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.
.
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.
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
if [ file exists /etc/resolv.conf ] then make a copy else print an error on screen fi
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
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
set -o ignoreeof
Now, try pressing [CTRL-d] Sample outputs:
Use "exit" to leave the shell.
Turn it off, enter:
set +o ignoreeof
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
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]$
vi ~/.bashrc
Add the following commands:
shopt -q -s cdspell
shopt -q -s checkwinsize
shopt -q -s extglob
shopt -s histappend
shopt -q -s cmdhist
set -o notify
set -o ignoreeof
ulimit -S -c 0 > /dev/null 2>&1
export HISTSIZE=5000
export HISTFILESIZE=5000
export HISTIGNORE='&:[ ]*'
export PAGER=less
export EDITOR=vim export VISUAL=vim export SVN_EDITOR="$VISUAL"
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)
export JAVA_HOME=/usr/lib/jvm/java-6-sun/jre
export PATH=$PATH:$ORACLE_HOME/bin:$HOME/bin:$JAVA_HOME/bin
/usr/bin/keychain $HOME/.ssh/id_dsa source $HOME/.keychain/$HOSTNAME-sh
source /etc/bash_completion
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'
alias bc='bc -l' alias diff='diff -u'
alias update='yum -y update'
alias dnstop='dnstop -l 5 eth1' alias vnstat='vnstat -i eth1'
alias grep='grep --color'
alias l.='ls -d .* --color=tty' alias ll='ls -l --color=tty' alias ls='ls --color=tty'
Use the :
See .
The is used to locate the binary, source, and manual page files for a command.
The is used display a short description about command. whatis command searches the manual page names and displays the manual page descriptions for a command:
• •
keeps a in buffer or a default file called ~/.
• •
Bash supports the following three simple :
• •
:
• •
Use to display list of all defined aliases.
Add user defined aliases to ~/ file.
If you want to add aliases for every user, place them either in or /etc/profile.d/useralias.sh file. Please note that you need to create /etc/profile.d/useralias.sh file.
User specific alias must be placed in ~/ ($HOME/) file.
Example ~/ script:
To ignore an alias called ls and run ls command, enter:
• •
It is quite easy to add colors to your prompt. Set green color prompt for normal user account:
Edit your ~/. or ~/.
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:
Edit ~/ file:
Add the following two shell
from Bash prompt howto
code taken from the official Arch Linux wiki
• •
Task: Make changes to your bash shell environment using and commands.
• •
A is nothing but an expression that evaluates to a (true or false).
Now, it makes no sense to use for comparisons. But, when you compare it with some value it becomes very useful. For example:
See for detailed explanation of each variable.
Disable which is used to logout of a (local or remote login session over ssh).
You can turn on or off the values of variables controlling optional behavior using the . To view a list of some of the currently configured option via shopt, enter:
Edit your ~/, enter:
Simply add the settings to ~/: