Upload
jwzumwalt
View
270
Download
0
Embed Size (px)
Citation preview
8/14/2019 Bash Shell Referance - Jan Zumwalt
1/45
This and many other develope references available at http:/neatinfo.com/d
ev_notes/_cheat-sheets
8/14/2019 Bash Shell Referance - Jan Zumwalt
2/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 2 of 45
Notes:
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
____________________________________________________________________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
8/14/2019 Bash Shell Referance - Jan Zumwalt
3/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 3 of 45
Table of Contents
Table of Contents ........................................... 3
Commands & Programs - Alphabetical ......... 4Langauages ......................... ........................ .... 4
Commands & Programs - by Function ............ 5Archives ...................... ......................... ............ 5Communication & Network ............................... 5Edit & View ........................ ...................... ......... 5File & Dir Management ......................... ............ 5Languages ........................ ...................... ......... 5Office Utilities ...................... .......................... ... 5Printer .............................................................. 5Process Management ...................... ................. 6Search and Patterns ..................... .................... 6System Administration ..................... ................. 6
Basic Directory Structure ................................ 7Common Backup Directories ............................ 7Log files ........................................................... 7Spool files ........................................................ 7Configuration files ......................... .................... 8Device files ........................ ...................... ......... 8Other Important files ..................... .................... 9X Window files ..................... ......................... .... 9
Special Characters ....................................... 10Input/Output .................................................. 10Preset Shell Parameters ............................... 10
Login environment ........................ .................. 11Shell internal settings ..................................... 11
Process ID variables....................................... 12ksh/bash additional features ........................... 12
Bash Shell Concepts .................................... 13Syntax ......................... ......................... .......... 13
Bash Startup & Kill ........................................ 13Configuration Files .............. .......................... . 13Invoking Shell ...................... .......................... . 14dot Command ..................... ........................ .. 14XWindow & KDE Startup ...................... .......... 15Background Processing ........................ .......... 15Terminating a Process ..................... ............... 15Environment ......................... ........................ .. 15
Built-in Shell Commands .............................. 17Parameters & Variables ................................ 18
Assigning a Variable ..................... .................. 18Referencing a Variable ................................... 18Special Variables....................... ..................... 18Position Parameters ..................... .................. 19Shift Command .................................... .......... 19Set Command ..................... ......................... .. 19Conditional Use of Variables........................... 20
The Environment .......................................... 21Exported variables ............................... ........... 21Common shell variables .................... .............. 21Regular Expressions ......................... .............. 21
Wild Cards ................................................... 22Wild Strings ...................................... .............. 22Wild Character .................... ......................... ... 22Match Lists ................................. .................... 22
Quoting ........................................................ 23Single Quotes ..................... ......................... ... 23Double Quotes .................... ......................... ... 23Single Character Escape .......................... ...... 23
I/O Redirection ............................................. 24Output Redirection ...................... .................... 24
Input Redirection ....................... ...................... 25Here Documents ....................... ...................... 25Pipes Connecting Commands ......... ........... 26
Unix Commands ........................................... 27Search Order ...................... ......................... ... 27Chmod Command ..................... ...................... 27Echo ..................... ....................... ................... 27Expr ......................... ......................... .............. 28False ........................................ ...................... 30True ......................... ......................... .............. 30Go Function ..................... ......................... ...... 30redo ......................... ......................... .............. 31Kill ............................................ ...................... 31
Shutdown ......................................... .............. 32Set Command ..................... ......................... ... 32Test ......................... ......................... .............. 33Trap Command ......................... ...................... 34
Conditional Statements ................................ 34If Statement ...................................... .............. 34While Statement ............................... .............. 36Until Command ............................................ ... 37For Command ..................... ......................... ... 37Case Command ........................ ...................... 37
Shell Functions ............................................. 38Functions vs. Scripts ......................... .............. 38Defining a Function ..................... .................... 38
Where to Define Functions ........................ ...... 39Status of Definitions ..................... ................... 39
Search Order................................................ 39Command Line Shell Invoking ...................... 40
Invoking ...................................... .................... 40
Debugging .................................................... 41Linux Bash Command Reference Sheet....... 42
8/14/2019 Bash Shell Referance - Jan Zumwalt
4/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 4 of 45
Commands & Programs - Alphabetical
adduser manage user accountawk search & editingat job schedulerbc calculator
cal calendarcalendar reminder servicecancel remove print jobs from queuecat concatenates or prints filescd change directorychgrp change group permissionschmod change file/dir permissionschown change owner permissionscmask sys def permission see umaskcmp compare two text filescomm find same lines of sorted filescompress compress filecp copy filescpio file archive programcron job scheduler
cu call another systemcut cut/paste columns of textdate date and timedd file copy programdf mounted file sys/drives infodiff difference between two filesdu file & dir disk usageecho shows argumentemacs editorenv show environment variablesex line-oriented text editoreqn format mathematical textfind find and act on filesfinger user infofork create child process
fsck file system check and fixftp file transfergrep search pattern and do actiongzip compress fileshead show first lines of filehistory print last commandsinfo like man, command infojoin join two columns of textkill terminate or send signalsless file viewerln create file linkslogin sign on to systemlp line printer managerlpc manage print jobslprm remove print jobs
lpstat status of print jobslpq status of print jobsls show directory contentsmail manage mailmailx advanced mail managementman manual of command infomesg permit or deny talk messagesmkdir create new directorymm macro print formattermore file viewer, use less instead
mount init make file sys or devicemv move or rename filesping transfer time & routenetstat transfer info
nroff print formatter, use mm insteadpasswd change login passwordpaste cut and paste columns of textpg file viewer, use less insteadping transfer time & routepostnews netnews writerpr format and print text fileps show program statuspstat show kernel infopwd print working directoryrcp remotely copy filesreadnews netnews managerrlogin remote loginrm remove filesrn netnews manager
rmdir remove directoriesrpm manage packagesscript saves bash session to filesed pattern editorshl shell managersort ort and merge text filesspell spelling checkershutdown halt or reboot systemsplit text editingstty set terminal optionstbl put tables into documentstail view last lines of text filetalk talk (type) to another usertar combine filestee split output
telnet net file managertime time infotroff typeset formattingumask usr default perm see cmaskumount remove file system or deviceuncompress expand compressed fileuniq remove dup lines of text fileuptime elapsed time since bootuucp file transfer between systemsuupick retrieve file sent via uutouuto Send file to another systemvi text editorwc word countwho who is logged into systemwrite write to another user
zcat display compressed file
Langauagescc c compilerf77 fortran compilermake source code managernasm assemblerpc pascal compilerperl perl compiler
8/14/2019 Bash Shell Referance - Jan Zumwalt
5/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 5 of 45
Commands & Programs - by Function
Archivescompress compress filecpio file archive programgzip compress filesrpm manage packagestar combine filesuncompress expand compressed filezcat display compressed file
Communication & Networkcu call another systemftp net file managergettynetstat transfer infoping transfer time & routeptyttyrcp remotely copy files
rlogin remote loginrsetstty set terminal optionstalk talk (type) to another usertee split outputtelnet net file managertermcaptsetuucp file transfer between systemsuupick retrieve file sent via uutouuto Send file to another system
Edit & Viewawk search, filter, edit
cat concatenates or prints filescmp compare two text filescomm find same lines of sorted filescut cut & paste columns of textdiff difference between two filesecho show argument(s)emacs editoreqn format mathematical textex line-oriented text editorhead show first lines of filejoin join two columns of textless file viewermore file viewer, use less insteadnroff prt formatter, use mm insteadpaste cut and paste columns of text
pg file viewer, use less insteadsed search, filter, editsort sort and merge text filessplit txt edittail view last lines of text filetbl put tables into documentsuniq remove duplicate linesvi text editor
File & Dir Managementcd change directorychgrp change group permissionschmod change file/dir permissionschown change owner permissions
cp copy filesdd file copy programdf mounted file sys & drive infodu file & dir disk usage
find find and act on filesfsck file system check and fixgrep search pat and act on fileftp file transferln create file linksls show directory contentsmkdir create new directorymount make file or dev availablemv move or rename filespath change shell environmentpwd print working directoryrm remove filesrmdir remove directoriesumount remove file system or deviceuucp file transfer between systems
uupick retrieve file sent via uutouuto Send file to another system
Languagescc c compilerf77 fortran compilergcc gcc compilerjava java compilermake source code managernasm assemblerpc pascal compilerperl perl compilertk tk compilertkl tkl compiler
Office Utilitiesbc calculatorcal calendarcalendar reminder servicedate date and timemail mail managmentmailx advanced mail managementpostnews netnews writerreadnews netnews mgr, use rn insteadrn netnews managerspell spelling checkertalk talk (type) to another usertime time infowc word count
who who is logged into systemwrite write to another user
Printercancel remove print jobs from queuelp line printer managerlpc manage print jobslprm remove print jobslpstat status of print jobslpq status of print jobsmm macro print formatternroff prt formatter, use mm insteadpr format and print text filetroff typeset formatting
8/14/2019 Bash Shell Referance - Jan Zumwalt
6/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 6 of 45
Process Managementat job schedulercron job schedulerdate date and timeenv show environment variablesexport send variable to shellfork create child processkill terminate or send signalps program statustee split output
Search and Patternsawk pattern scanningfind find and act on filesgrep search pat and act on file
sed pattern editorsort sort and merge text filesnohup prog running after logoffps program statustee split output
System Administrationadduser manage user accountchgrp change group permissionschmod change file/dir permissionschown change owner permissions
cmask sys default perm see umaskdate date and timeecho shows argumentenv show environment variablesfind find and act on filesfinger user infogrep search pattern & do actionshistory show command historyinfo like man, command infologin sign on to systemmail manage mailmailx advanced mail managementman manual of command infomesg permit or deny talk messagespasswd change login passwordpath change shell environmentpstat show kernel infoscript saves bash session to fileshl shell managershutdown halt or reboot systemstty set terminal optionstime time infoumount remove file system or deviceumask usr default perm see cmaskuptime elapsed time since bootwho who is logged into system
8/14/2019 Bash Shell Referance - Jan Zumwalt
7/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 7 of 45
Basic Directory Structure
/ ................................. ;root directory
/bin ............................... ;system commands
/boot .............................. ;kernel & boot files
/dev ............................... ;device drivers/etc ............................... ;pub system configuration files
/home .............................. ;user private files & settings
/lib ............................... ;c compiler libraries
/lost+found ........................ ;files fragments are saved here
/mnt ............................... ;external file systems and devices
/opt ............................... ;optional programs, i.e. KDE
/proc .............................. ;process files
/root ............................. ;roots custom files & settings
/sbin .............................. ;superuser commands needed to start
/tmp ............................... ;system temporary files
/usr ............................... ;pub cmds & prop, can be read-only
/usr/bin ........................... ;pub commands
/usr/doc ........................... ;pub info files
/usr/man ........................... ;pub man files/usr/include ....................... ;pub c header files
/usr/include/g++ ................... ;pub c++ header files
/usr/lib ........................... ;pub libraries
/usr/local ......................... ;extensions independent of distro
/usr/sbin .......................... ;superuser commands
/usr/src ........................... ;pub application source files
/usr/src/linux ..................... ;kernel source files
/usr/tmp ........................... ;pub temporary files
/var ............................... ;config files, link to /usr
/var/tmp ........................... ;pub temporary files
Common Backup Directories/etc/lilo.conf ..................... ;Lilos boot loader configuration/boot/grub ......................... ;grubs boot loader configuration
/etc/fstab ......................... ;disk partition table configuration
/etc/modules.conf .................. ;modules to load % their parameters
/etc/isapnp.conf ................... ;ISA Plug & Play hardware parameters
/etc/Xll/XF86Config-4 .............. ;Xs settings
/etc/X11/XF86Config ................ Xs settings
/etc/cups .......................... ;CUPSs printer settings
/etc/printcap ..................... ;lpr print settings
/etc/bashrc ........................ ;bash shell system-wide configuration
/etc/profile ....................... ;system-wide environment
/etc/crontab ....................... ;cron jobs to be executed
/etc/rc.d .......................... ;run level settings
/etc/inittab ....................... ;sets default run level & settings/etc/ssh ........................... ;ssh settings for secure remote access
/root ............................. ;roots custom files & settings
/home .............................. ;users custom files & settings
Log files/var/log ;log files
Spool files/usr/spool ;buffer for file xfer, etc
/usr/spool/lp ;buffer for printer
8/14/2019 Bash Shell Referance - Jan Zumwalt
8/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 8 of 45
Configuration files/boot/grub ......................... ;grubs boot loader configuration
/etc/bashrc ........................ ;bash shell system-wide configuration
/etc/crontab ....................... ;cron jobs to be executed
/etc/cups .......................... ;CUPSs printer settings
/etc/DIR_COLORS .................... ;ls color settings
/etc/fstab ......................... ;disk partition table configuration/etc/group ........................ ;user groups
/etc/hosts ........................ ;hostname to address table
/etc/initd.conf ................... ;net services, ftp, telnet, etc
/etc/inittab ....................... ;sets default run level & settings
/etc/isapnp.conf ................... ;ISA Plug & Play hardware parameters
/etc/lilo.conf ..................... ;lilos boot loader configuration
/etc/modules.conf .................. ;modules to load & their parameters
/etc/passwd ....................... ;usr info, shell pref, home dir, etc
/etc/printcap ..................... ;lpr print settings
/etc/profile ....................... ;shells login script
/etc/rc.config ..................... ;sys config settings read during boot
/etc/rc.d .......................... ;run level settings
/etc/shadow ....................... ;passwords
/etc/ssh ........................... ;ssh settings for secure remote access
/etc/syslogd.conf ................. ;syslog daemon settings
/etc/XF86Config .................... ;X window settings
/etc/X11/XF86Config ................ ;Xs settings
~/home/.profile .................... ;usr custom environment settings
/sbin/init.d ....................... ;scripts for system start
Device files/dev/fd0fd1 ....................... ;floppy
/dev/hda ........................... ;1st IDE & CDROM drive
/dev/hda1hda15 .................... ;1st IDE & CDROM drive partitions
/dev/hdb ........................... ;2nd IDE & CDROM drive
/dev/hdb1hdb15 .................... ;2nd IDE & CDROM drive partitions
/dev/sda ........................... ;1st SCSI & USB drive
/dev/sda1sda15 .................... ;1st SCSI & USB drive partitions
/dev/sdb ........................... ;2nd SCSI & USB drive
/dev/sdb1sdb15 .................... ;2nd SCSI & USB drive partitions
/dev/sdc... ........................ ;3rd SCSI & USB drive...
/dev/cdrom ......................... ;cdrom drive, linked to driver
/dev/hda - hdd ..................... ;ATAPI IDE cdrom drive
/dev/scd0 scd1 ................... ;SCSI cdrom drive
/dev/rmt0 .......................... ;1st SCSI tape, auto rewinds
/dev/nrmt0 ......................... ;1st SCSI tape, no auto rewind
/dev/ftape ......................... ;1st floppy tape, auto rewinds
/dev/ntape ......................... ;1st floppy tape, no auto rewind
/dev/mouse ......................... ;mouse
/dev/atibm ......................... ;ati graphics card mouse/dev/logibm ........................ ;logitech mouse
/dev/inportbm ...................... ;ps/2 bus mouse
/dev/modem ......................... ;link to com port with modem
/dev/ttS0ttS3 ..................... ;serial port
/dev/cua0cua3 ..................... ;serial port
/dev/lp0lp2 ....................... ;parallel port
/dev/tty1tty8 ..................... ;virtual serial console
/dev/null .......................... ;null device
/dev/zero .......................... ;output endless null bytes
8/14/2019 Bash Shell Referance - Jan Zumwalt
9/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 9 of 45
Other Important files/usr/linux ......................... ;kernel source
/etc/skel .......................... ;new user skeleton files copied to users
/home/ ........................... user personal and setup files
.profle ............................ usr login script
.bashrc ............................ usr bash config
.exrc .............................. usr vi config
.xinitrc ........................... usr x win startup
.fvwmrc ............................ fvwm win mgr startup
.ctwmrc ............................ ctwm win mgr startup
.openwin-menu ...................... olvwm win mgr startup
X Window filesComing soon ........................ kernel source
8/14/2019 Bash Shell Referance - Jan Zumwalt
10/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 10 of 45
Special Characters
| pipe connects two commands; command separator
& run process in background; default stdin from /dev/null
&& only run command if previous command completed successfully|| only run following command if previous command failed
enclose string to be taken literally
enclose string to have parameter and cmd substitution only
\ ignore special meaning of following character
? match single character in filename
* match 0 or more characters in filename
[chars] match any of chars (pair separated by a matches a range)[!chars] match any exceptchars
in-line command execution
Input/Output
All of these operators may be preceded by an optional file descriptor. Defaults
are shown in parentheses.
< file use file as stdin
> file use file as stdout
>> file like > but append to file if it exists
&n duplicate output file desc. from n (stdout)
&- close stdout
8/14/2019 Bash Shell Referance - Jan Zumwalt
11/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 11 of 45
${datafile=default}Similar to the above, except ifdatafile has not been defined, set it to the string "default".
${datafile+default}If variable datafile has been defined, use the string "default", otherwise use null. In this case
the actual value $datafile is not used.
Substitute the value of$datafile, if it has been defined, otherwise display datafile: error
message. This is used for diagnostics when a variable should have been set and there is nosensible default value to use.
$name only checks if name is set
$name: checks if name is set and non-NULL
${var} use braces to delimit shell variable name${vartext} use var if set, else use word
${var=text} use var if set, also set name to word
${var?text} use var if set, otherwise print word and exit
${var+text} use word if var set, otherwise use nothing
Example ${datafile?"error message"} debug message if var is not set
Login environment$EDITOR If set, this contains the name of the program which the user prefers to use for text file
editing. A program which needs to have the user manually edit a file might choose tostart up this program instead of some built-in default (e.g. "crontab -e". This alsodetermines the default command-line-editing behavior in interactive shells.
$USER currently logged-in username
$LOGNAME Preset to the.
$PATH The list of directories that will be searched for external commands. You can change thisin a script to make sure you get the programs you intend, and don't accidentally getother versions which might have been installed.
$TERM The terminal type in which the shell session is currently. Usually "xterm" or "vt100".
Many programs need to know this to figure out what special character sequences tosend to achieve special effects.
$PAGER If set, this contains the name of the program which the user prefers to use for text fileviewing. Usually set to "more" or "less" or something similar. Many programs which
need to present multipage information to the user will respect this setting (e.g.man).This isn't actually used by the shell itself, but shell scripts should honour it if they needto page output to the user.
$SHELL name of default shell
$CDPATH search path for cd command
$HOME home directory for cd command
$IFS field separators (space, tab. newline)$MAIL name of a mail file, if any
$MAILCHECK check for mail every n seconds$MAILPATH fnames to check new mail (: separator; fname may be followed by
%message)
$PS1 primary prompt string ($)
$PS2 secondary prompt string (>)
$SHACCT accounting file for user shell procedures
name=word set name to specified word
Shell internal settings$PWD Always set the current working directory (readonly)$OLDPWD The previous directory (before the most recent cd command)
$? (readonly) Set to the exit status of the last command run, so you can test success or failure. very
command resets this so it must be saved immediately if you want to use it later.
8/14/2019 Bash Shell Referance - Jan Zumwalt
12/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 12 of 45
$- Option flags of current shell command.$IFS
Internal Field Separators: the set of characters (normally space and tab) which are used to parsea command line into separate arguments. This may be set by the user for special purposes, butthings get very confusing if it isn't changed back.
Process ID variables$$ (readonly)Set to the process ID of the current shell - useful in making unique temporary files, e.g./tmp/$0.$$
$PPID (readonly) Set to the process ID of the parent process of this shell - useful for discovering howthe script was called.
$! (readonly) Process ID of the last command started in background.
ksh/bash additional features$SECONDS (readonly)
Integer number of seconds since this shell was started. Can be used for timing commands.$RANDOM
Every time it is valuated, $RANDOMreturns a random integer in the range 0-32k. RANDOMmay beset to "seed" the random number generator.
$LINENO (readonly)Always evaluates to the current line number of the script being executed - useful for debugging.
8/14/2019 Bash Shell Referance - Jan Zumwalt
13/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 13 of 45
Bash Shell Concepts
SyntaxThis section provides a reference for commands built into the shell. Words with-in
are substitutes for unprintable characters, for example . may also be
used for mandatory options, files, or input.
Whitespace consists of one or more and/or characters. In addition,commands are terminated by any of the following characters: ; & () ^ . Boldface represents words typed exactly as they appear. Italics
represent words to be substitutedfor things such as filenames.
Note that if an italicized word is plural (i.e. files), multiple arguments are
permitted. A digit at the end of a word such as var1 indicates a unique name so
it can be referenced in the description. The following substitutable words are
used in this reference:
file or fname: a filename, pathname, or variable of one
list one or more pipelines that can be separated by ;, &, &&, || andoptionally be terminated by ; or &.
n an integer
name the name of a shell variable
oct an octal number
pat explained in conjunction with the case command.
word a generic argument; a word. Quoting may be necessary if it contains
special characters.
Bash Startup & Kill
Configuration Files
The /etc/profile is the main startup file for all bash shells. It usually looks inthe users home directory for further instructions. The home directory should
contain one or more of the following bash startup files, which contain commands
that apply only to the current user's bash session:
$HOME/.bash_profile
$HOME/.bash_login$HOME/profile
$HOME/.bash_rc$HOME/.bash_logout
To understand how bash uses startup files, consider the difference between a login
shell and a non-login shell. A login shell is created when a user enters the
operating environment using a name and password account. A non-login shell is
created when an additional bash shell is launched within the user session, as you
do when you open a terminal window in X, or execute a shell program.
To starta shell, bash consults the following files in the specified order:
Login Shell Non-Login Shell
1. /etc/profile 1. $HOME/bash.rc
2. $HOME/.bash_profile usually points to ->
3. $HOME/.bash_login
4. $HOME/profile
When you start a non-login shell, bash consults only one startup file,
Because login and non-login shells use different startup files, the shells created
may differ. Most Linux distributions contain an automatically generated
8/14/2019 Bash Shell Referance - Jan Zumwalt
14/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 14 of 45
~./bash_profile that contains a script that automatically executes the commandsplaced in ~/bash_rc. This script ensures that the login shell will be configured
like the non-login shell. To add a command that is automatically executed when any
user begins a login shell, add the command to /etc/profile. You'll need to switch
to superuserstatus to edit this file.
To add a command that is executed when you start a login shell in your own user
account, use ~/bash.profile for commands that must be executed before commandscontained in ~/.bash_login or ~/profile. Use ~/profile for commands that must be
executed only after the shell executes the commands found in ~/.bash.profile and
~/bash_login.
To add a command that is executed when you start a non-login shell, use ~/.bashrc.
Invoking ShellThis section shows the syntax for invocation of the shell. In order to parse the
command line properly, the arguments must be separated in a manner the shell
understands. Whitespace and/or punctuation is used. Whitespace consists of one or
more space characters, tab characters, and/or the end of line character.
Punctuation consists of the characters () ; | >>
The end of a command line is generally signified by entering the newline
character, usually represented by the key. You can also separate commands
with a semicolon (;).
The pound sign (#) character indicates the beginning of a comment to the shell.
All characters from the # to the end of the line are ignored.
sh [options] [args]
Options:
a mark modified export variablesc cmdexecute cmd, default reads cmds from file in first entry of args.
e if non-interactive, exit if a command fails
f disable wildcardingh locate and remember functions on definition instead of on execution
i set interactive mode
k all keyword arguments placed in environment
n read commands without executing themr set restricted mode
s read commands from stdin
t read and execute one command, then exit
u set error upon substituting an unset variable
v print input lines as read
x print commands and arguments as executed
All options except c, i, r, s can be set or unset within the shell with the set
command.
dot Command
The shell has a built-in command represented by a period . which is pronounced
dot. This command reads a file of commands without creating a sub-shell. This
means you can change our environment by interpreting a file with the dot command.
For example. if you modified your .profile you could re-interpret it without
having to log back in by entering:
. .profile
If you create various files to set up different environments for yourself, you
will probably want to set different values for PSI so you know which environment
you are in.
8/14/2019 Bash Shell Referance - Jan Zumwalt
15/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 15 of 45
XWindow & KDE StartupFor completeness the xwin startup is briefly discussed here. The xwindow system should always bestarted using the startx command which is designed to get things going. A tremendous amount ofprograms and synchronization is needed for the GUI to successfully load.
startx
8/14/2019 Bash Shell Referance - Jan Zumwalt
16/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 16 of 45
commands to alter your environment in this file. Whenever you log in, the shell
interprets this file.
If you set a shell variable and want it to be exportedto the environment so that
subsequent shells will receive its value, you must put it in an export statement.
You may also want to define some shell functions as abbreviations for commonly
used commands and place them in .profile. The following is a sample .profile
export PATH TERM CDPATHPATH=$HOME/bin:/bin:/usr/bin:.
CDPATH=:$HQME:/usr/localPS1=Hi Phil >TERM=h19
umask 027news n
The first line establishes three variables to be exported to the environment.
Next, the variable PATH is set to a string of directory names. Each name is
separated by a colon :. This establishes where the shell will search for commands.
In this example, it first searches sub-directory bin of your home (login)
directory, then /bin, then /usr/bin, and finally the current directory represented
by a dot.
CDPATH establishes where the cd command looks for a directory that does not
contain a leading slash. By default, it would look in your current directory. By
assigning a new value to CDPATH, the cd command would first look in the current
directory (identified by the: immediately following the =, then look in your home
directory, and finally /usr/local.
PS1 establishes your primary prompt string. This string will appear instead of the
default % as the shell prompt.
The TERM variable is used to establish the terminal type you use. If you do not
always use the same type of terminal, this line can contain a reference to the
test command to conditionally establish terminal type.
The umask command sets the file creation mask which is used to limit the access
capabilities of any files that you create. This particular value (027) establishes
the maximum access permissions as anything for owner, read and execute for group
and nothing for other.
The -n option is to print out any news items that are current and then update the
time stamp file that it uses to keep track of what you have read.
8/14/2019 Bash Shell Referance - Jan Zumwalt
17/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 17 of 45
Built-in Shell Commands
# start of comment: terminated by a newline.file read and execute commands from file
: null command: returns 0 exit status
[ see testbreak [n] exit from enclosing for or while loop
cd [file] change current directory to file
continue [n] do next iteration of enclosing for or while
echo [words] echo words (see echo in Appx. B)
eval [words] evaluate words and execute result
exit [words] execute words in place of shell
exit [n] exit with return value nexport [names] export names to environment of commands
getopts parse parameters and options
hash [r] [files] remember locations of files; with no files shows hash info
r forgets all remembered locations
newgrp [words] same as exec newgrp words
pwd print working directory name
readnames read stdin and assign to namesreadonly [names] mark names read-only;
print list if no names, return n, exit with return value n
with no n return status of last command
set [options] [words]
set flags (aefhkntuvx- are valid). words set positional
parameters
set [+options] [words]
unset flags
shift [n] rename positional parameters; $n+1 =$1... (n defaults to 1)
test evaluate conditional expressions
times print accumulated process times
trap [word][sigs]
execute word if signal in sigs receivedno word or sigs print traps
no word reset sigs to entry defaults
word is null string ignore sigs
sigs is 0 execute word on exit from shell
type files show how shell would interpret each file
ulimit [options] [n]
limit size to n (if no n. print current limits)
f files created by child processes (n blocks default)
p change pipe size to n
umask [oct] set file creation permissions mask (see chmod)
unset [names] unset variables or functions names
wait [n] wait for process n; if no n, wait for all children
8/14/2019 Bash Shell Referance - Jan Zumwalt
18/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 18 of 45
Parameters & Variables
Shell variables can be used to remember values that you intend to use later. Shell
variable names can be made up of letters a-z A-Z and the underscore _ character.
There are no data types in the shell. All shell variables are character strings.These shell variables are built-in, named save areas that you can create by
referencing them by name. You can perform arithmetic functions on shell variables
using the exprcommand.
Assigning a VariableIn order to assign a string to a variable you enter what looks like an algebraic
expression. Note that there must be no spaces around the equals = character. For
example, to assign the string joe to the shell variable worker...
worker=joe
If the variable contains any special characters, including whitespace, you need to
quote it. For example...
worker=joe smith
The double quotes do not become part of the string, they just prevent the
interpretation of the special meaning of the space character in the assignment
statement.
Referencing a VariableTo reference a shell variable, precede its name by the dollar sign $ character.
For example,
meal=steak
echo $salad ;would show: steak
If you need to insert a variable reference with other characters, you can use
braces {} to delimit the variable name.echo Eat ${meal}and milk. ;would show Eat steak and milk.
Whereas...
echo Eat $mealand milk.
would attempt to reference a shell variable $mealand that does not exist.
You can also assign command names to shell variables. For example,
cmd=ps
option=-ef$cmd $option ;performs commandps -ef
Special VariablesThere are built in variables too. For example, $PS1 is your primary shell promptstring (usually %). Another example is $$, the process number of the current
shell. This is commonly used to create unique filenames. The following statement
would be a good way to create a unique filename. It could then be referenced by a
reference to the shell variable z. z might equel something like xyz8423.
z=xyz$$Another special variable is $? which contains the exit status for the last command
executed. $? is set to 0 if the command executed successfully, non-0 otherwise.
Commands return a different non-zero exit status depending on the type of failure.
You can look at values of individual variables by referencing the variable in an
echo command. For example, the following command displays the values of the HOME
and TER\1 shell variables:
echo $HOME $TERM
8/14/2019 Bash Shell Referance - Jan Zumwalt
19/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 19 of 45
The set command displays the values of all shell variables (and shell functions).
Position ParametersWhen you start a shell script you can pass parameters to it. For example, you may
need to pass a file name. These parameters are placed on the invocation line
following the command and are called positional parameters. These parameters arereferenced in the same manner as shell variables.
Description Variable
---------------------------------------------number of positional parameters $#
command name that invoked script $01st parameter $1
2nd parameter $2etc...
For example, the following command...
ls l *
Would have the following parameters,
Description Variable Value-------------------------------------------------------------------
number of positional parameters $# 2command name that invoked script $0 ls
1st parameter $1 -l
2nd parameter $2 *etc...
Parameters can also be passed by name by preceding the command that invokes the
shell script with assignments to variables. For example, the following command
will invoke the shell program cool with shell variable first set to 5 and shell
variable last set to 10.first=5 last=10 cool
These assignments do not affect the variables in the current shell. They are
merely named passed parameters, commonly called keyword parameters.
Shift CommandShift deletes the first positional parameter $1 and shifts each subsequent
parameter one place to the left. In other words, $2 becomes $1, $3 becomes $2 and
so forth.
Set CommandThe set command allows you to do three things:
set shell options
change positional parameters
display set variables
The shell, like most UNIX commands, has options which may appear on the command
line. Unlike other commands, many of these options can be changed by the use of
the set command.
The positional parameters ($1. $2. ) can be changed using set. For example, to set
the first three positional parameters ($1, $2, and $3, to uno, dose, trace, you
would use the following set command...
set uno dose trace
After this command, the command
8/14/2019 Bash Shell Referance - Jan Zumwalt
20/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 20 of 45
echo $2
for example, would print
dose
Finally, set with no options prints a list of all shell variables (and functions)
that are currently defined.
Conditional Use of VariablesSometimes it is desirable to be able to conditionally use values of a shell
variable. For example, if a variable is missing it may be desirable to insert a
default value. This can be done by an extension of the variable reference notation
using braces. The expression ${var} is a reference to the value of the shell
variable var. The following additional forms are available. Note that without the
: in the expression, the variable is only checked to see if it is set; whether or
not the variable is non-null is not considered.
${var:-word} Substitute value of var if set and non-null; otherwise
substitute word.
${var:=word} If variable is not set or is null, set it to word. Then use
value of var. Note that this cannot be used to assign values to
positional parameters.
${var:?word} Use value of varif set and non-null. Otherwise, print wordand
exit from the shell, If wordis omitted, parameter null or not
set is printed.
${var:+word} If var is set and non-null, word is substituted, Otherwise
nothing is substituted.
The following version of append will append to the file /tmp/app.data if you do
not specify a file name on the invocation line. In other words, if $1 is not set,
the file /tmp/app.data is used.
# append version 1
echo control-D to terminate
cat >> ${l:-/tmp/app.data}
The following version of append complains when it is invoked without a filename on
the command line.
# append version 2echo controlD to terminate:
cat >>${l:?filename required)
This version prints out the message append: 1:
filename required if you enter the command with no parameters. Unfortunately. the
error message is printed out after the information message from echo. Version 4
gets around this problem by assigning the parameter to a shell variable named fn
which Is then used in the cat command if the substitute doesnt tail.
# append version 3
fn=${1:?filename required}echo controlD to terminate:
cat >>$fn
8/14/2019 Bash Shell Referance - Jan Zumwalt
21/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 21 of 45
The Environment
The environment consists of pairs of names and values. When a shell is started
(either from logging into the shell or from starting a sub-shell) the shell scans
the environment and creates a variable with the related value for each pair found.
Exported variables
When a one program invokes another program, the child program receives all of the
exportedenvironment variables of the parent.
By default, environment variables are notexported.
Shell variables can be bound to the environment by use of the export command. If a
variable is named in an export statement, any future shells will inherit this new
variable and its associated value. Note, however, that you cannot pass information
back to a calling shell through this mechanism.
Common shell variables
Most shells have the following set:
variable description
DISPLAY tells X11 on which display to open windows
EDITOR default text editor; usually emacs or vim
HOME path to user's home directory; same as ~
PAGER default page-scroller to use; usually less
PWD current directory; same as output of pwd
SHELL path to the current shellTERM current terminal type
USER account name of current user
The statement export with no arguments will display all variables that are
currently being exported. One of these, $HOME, is the pathname of your login
directory, is initially extracted at login time from your password file entry.
For example, the new version of append looks in the environment for a variable
named afile to determine what file to append to if none is specified on the
command line.
# append version 4fn=${1:${afile:?filename reqd}}echo appending to $fn
echo control-D to terminate:
cat >> $fn
Regular ExpressionsNote:multiple res may be concatenated
c the character c
\c character c (for special characters)
. any character except a newline
[str] any one character in str ([a-b] means all in range a thru b)
8/14/2019 Bash Shell Referance - Jan Zumwalt
22/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 22 of 45
[^str] any character except newline or one from strre* 0 or more occurrences of 1 character re
re\{m,n\} m thru n occurrences of 1 character re
\(re\) group re for later reference
\n nth re in\(..\)
^ beginning of line (not in expr)
$ end of line
default re last re encountered
& put matched string in replacement
% same as last replacement
Wild CardsWild StringsThe asterisk * matches any number of characters. In other words, 0 or more of any
characters. For example, if you wanted a long list of the characteristics of all
files in the current directory whose names contained the string test. you could
use the following command:
ls l *sample*
The first * means that there can be 0 or more characters before the literal string
sample and the second * means there can be 0 or more after the string.
Therefore, files with names like sample01, xsample, and ysample33.db will all be
listed.
Wild CharacterSingle character made with the question mark ?. For example, a long listing of all
files whose names begin with z and are exactly three characters long would be
printed by the command...
ls l z??
Match ListsA third kind of wildcard is a match list. The syntax is [list] here list is thelist of characters to be matched. For example, the following echo command will
show all the file names whose first letter is a, second letter is b or c, and
third letter is d.
ls l a[bc]d
A range can be specified by using a dash, so the following would match files whose
names begin with w, second letter is h,I,j,k, third n, and forth x,y, or z.
ls l w[h-knx-z]
The three kinds of wildcards can be combined to perform matches. For example. the
following command would echo all file names whose third letter is x,y, or z.
echo ??[x-z]
The exclamation ! character can be used to reverse a comparison. It must appear
as the first character inside the brackets. For example, the following command
would produce a long list of all files whose names do not start with a lower case
letter:
ls l [!a-z]*
Testing Wildcards
The use of wildcards can be dangerous. It is very easy to inadvertently remove the
wrong files by using the rmcommand in conjunction with wildcards. If you are notsure what files will be effected, you can use the echo command to test the
pattern.
8/14/2019 Bash Shell Referance - Jan Zumwalt
23/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 23 of 45
Quoting
It is necessary to quote strings in order to prevent the shell from treating
various characters as special. You may need to quote a string to prevent the shell
from erroneously interpreting the special meaning of characters such as * or?.
Single QuotesThe apostrophe or single quote is used to indicate that all characters in the
enclosed string are to be taken literally. For example,
echo *[xyz]??
would echo the string *[xvz]?? rather than any matched file names.
Double QuotesThe double quote tells the shell to interpret only the special characters,
dollar sign $, and the backquote `. The special meaning of other characters is not
interpreted within double quotes.
Single Character EscapeThe special meaning of a single character can be escaped by preceding it with a
backslash \.
echo can\t
will print cant. Double quotes could have been used here but there will be times
when the escape character will be the only answer.
echo dont
The backslash also prevents the interpretation of the newline character. This
means that you can continue a command line by entering a \ before the new line and
then continue typing on the next line.
See the Difference?The following statements illustrate the difference between quotes...
# assign * asterisk to variable xy.
echo $xy ;prints $xy
echo $xy ;prints *
echo $xy ;prints
echo \$xy ;prints $xy
1) The first example prints $xy because the $ is protected from interpretationof its special meaning.
2) In the second line, echo prints *, the value of the shell variable me is anasterisk.
3) The third echo lists all files. The shell first substitutes $xy to itsvalue the re-scans the line. It is as if you had typed echo *.4) And the last statement uses the escape character \ to force the $ to be
interpreted as a regular character. Therefore, $xy is shown.
BackquoteThe backquote (grave accent) ` tells the shell to treat the enclosed string as a
command. The command is executed and the resulting string (output from the
command) is substituted in the command line. One use is to assign values to shell
variables.
echo `date`
8/14/2019 Bash Shell Referance - Jan Zumwalt
24/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 24 of 45
I/O Redirection
Note that in redirection, no filename expansion takes place. Therefore, any
occurrence of shell meta characters such as *or ? is treated literally.
There are three file descriptors which are normally connected to your terminal.Redirection is the process of changing the connections from your terminal to a
file or a program. The three file descriptors are...
Name descriptor description---------------------------------------------------------------------
stdin 0 standard, default input
stdout 1 standard output, default outputstderr 2 standard error, default error messages
Output RedirectionBoth stdout and stderrcan be redirected to a file. To create (or truncate) a file
and send standard output to a file, the >operator is used. For example. to send
the standard output of the date command to file named sample, use the followingcommand:
date > sample
Note: Using > causes a file with that name to be created and input sent to it. If
the file already exists, it will be erased and only the new information will be
added. To create a new file if none exists and add to the end of an existing file,
use >>. Therefore, running date > twice will erase the first date.
date > sampledate > sample
Now, running date >> will continue to add each date line to the end of the file.
The >> will save both commands output.
date >> sample
date >> sample
Note that since both the > and >> operators are punctuation, you do not need to
include spaces around them. The following three command lines are interpreted
identically:
PS ef>stats
PS ef > statsps ef>stats
To redirect standard error you use the same operators but precede them by the file
descriptor number (in this case 2) of standard error. For example, to run cc on
the file test.c and send errors to a file, you could use the following command...
cc test.c 2 > error.log
Because the redirection commands are interpreted by the shell, they are never seen
by the actual program that invokes it. Thus, where the redirection appears in the
command line is unimportant. The following command would be equivalent to the one
above...
cc 2 > error.log test.c
The operator >& can be used to duplicate an existing file descriptor. This
basically means that the two output streams are merged. For example, if you wanted
to run thepr command on files datal, data2, and data3 and merge the output and
error outputs into file all.log, you could use the following command...
pr data[123] > all.log 2>&l
8/14/2019 Bash Shell Referance - Jan Zumwalt
25/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 25 of 45
This command says to redirect standard output to the file all.log and create file
descriptor 2 by making a copy of file descriptor 1, the descriptor number for
stdout.
It you want to redirect stdout or stderr for multiple commands, you can use the
exec built-in function with redirection. The redirection will remain in effect
until another exec command with redirection is given. Note that /dev/tty is a
filename for your terminal. You can always use it to send output directly to the
terminal or redirect output back to the terminal.
For example, the following set of commands on your current stdout, sends the
output of theps and who commands to the file myout, to the terminal, sends the
output of date to my out and finally resets the standard output back to theterminal:
echo 1,2,3 test ;prints stdout message 1,2,3 test
exec > myout ;change stdout to a file
ps ;commands now sent to file myout
who
echo temporary redirect > /dev/tty ;echo temporary redirect
date ;date is sent to file myout
exec >/dev/tty ;stdout set back to terminalecho back to normal ;echo now goes to terminal
The operator >&- will close standard output. Like all the other operators in this
section, preceding it with a file descriptor number (i.e. 2 for stderr) causes it
to refer to a different file descriptor.
If you are running a command and want to discard its output you can redirect it to
the special file /dev/null. This is bit heaven , the output is sent, never to be
seen again.
Input RedirectionMany commands will read input from either a file named on the command line or from
stdin. The wc command is a good example. The two command lines below do basicallythe same thing. The difference is that in the first line, the wc program is
actually opening and reading the file /etc/passwd, whereas the second example has
the shell redirect stdout input from the file /etc/passwd before the wc program is
executed.
wc /etc/passwdwc
8/14/2019 Bash Shell Referance - Jan Zumwalt
26/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 26 of 45
How are you?
mama cries
Note that both parameter and command substitution are performed on the EOF
indicator word. Once performed, a literal comparison is performed to find the
matching word.
Normally, parameter and command substitution are performed on the input, so it is
necessary to use the backslash \ to escape the special meaning of \, $, and . If,
however, you quote any part of the EOF indicator word, shell processing of the
input is turned off. The following script sends the message exactly as it appears
with no parameter substitution, to user joe using the mail command.
mail joe
8/14/2019 Bash Shell Referance - Jan Zumwalt
27/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 27 of 45
Unix Commands
Some commands, although not part of the shell, are necessary to do useful work
with the shell. The main difference to the user is that these commands will take
slightly longer to execute because they must be loaded from the file system. Infact, some commands started out as separate programs and were later added to the
shell to speed execution, test is an example of such a command.
Search Order
When you enter a command, the shell first checks to see if it is one of the
commands built into the shell. Second, it checks to see if it is a shell function.
If the command isnt a built-in or a shell function, the shell searches the
directories listed in sour PATH shell variable in the order listed to try to
locate the command. This means that shell functions override commands that are
stored in files but built-in commands always override shell functions.
The type command, a shell built-in command, can be used to determine where theshell will locate a command. Just enter type followed by the command
name and the shell will display where it located the command.
Chmod Command
chmod ;change permissions of a file or directory
mode can be numeric or symbolic. The symbolic case consists of the form
[agou][+=][rstwx] where:
a all default (group, other, user)
g group access permissions
o other access permissionsu user access permissions
+ add the permission to status of files remove the permission from status of files
= set the permission of files to specified valuer read permission
s set owner-ID or group-ID on execution save text mode
w write permission
x execute permission Multiple symbolic modes separated by commas
The numeric case is formed from the following columns:
4000 set user ID on execution
2000 set group ID on execution
1000 set sticky bit (leave program in memory as long as possible)
0X00 owner permission, X added 04 (read), 02 (write), 01 (execute)00X0 group permission, X added 04 (read), 02 (write), 01 (execute)
000X other permission, X added 04 (read), 02 (write), 01 (execute)
example:
0744 owner=read, write, execute group&other=read only
0660 owner and group may read or write
Echo
echo [message] ;echo message to stdout
Note: special escape conventions (place string in quotes)
\b backspace
\c print line without newline form feed
\n newline
\n octal val (8 bits), n must start w/ 0 carriage ret
8/14/2019 Bash Shell Referance - Jan Zumwalt
28/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 28 of 45
\t tab
\\ backslash
Expr
expr args ;evaluate expression
Arguments must be separated by blanks, are evaluated as follows.A \ indicates that the following character must be escaped:
expr1\|expr2 returns expr1 if neither null nor 0; else expr2expr1\&expr2 returns expr1 if neither expris null or 0; 0 otherwise
expr1 cmpop expr2 returns result of integer compare if both args are ints;
otherwise, returns result of lexical compare
cmpop is:
= equal \> greater than
>= greater or equal
\< less than
\
8/14/2019 Bash Shell Referance - Jan Zumwalt
29/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 29 of 45
will print out 5+5, not the value 10 that you might have expected. This is where
the expr command comes in. expr treats its arguments as operators and operands and
performs arithmetic and comparison operations on them. There are two catches:
integer (not floating point) arithmetic is performed and each operator and each
operand must be passed to expr as a separate argument.
Here are some simple examples:
expr 5 + 3
prints out 8.
expr 12 / 3 + 9
prints out 13, unfortunately,
expr 5 * 3
prints out expr: syntax error. This is because the shell expands the * into a list
of filenames in your current directory. Escaping the *, either with a backslash or
quotes, will solve the problem as in any of the following:
expr5\*3 #use\
expr 5 '*/ 3 # or expr 5 "*" 3 # or
Note, however, that you cannot just put quotes around the complete expression as
in 5 * 3. This would cause the shell to pass the whole expression as one
argument. expr would just print out the string rather than evaluate it.
Expanding on this idea, shell variables can be inserted into expressions and we
have shell arithmetic. For example,
expr $count + 1
would print out the value of shell variable count plus 1. By using backquotes we
can get the shell to
execute the expr command and assign the result to a shell variable. Thus, we can
increment shell variables.
count=expr $count + 1
Using this capability it is easy to write a primitive version of the pg utility.
In this version, standard input is read and output pauses every 20 lines. It is
restarted by entering a return.
# dumb_pgcount=0while line
do
count=expr $count + 1if [ $count eq 20 ] ; then
read stuff
8/14/2019 Bash Shell Referance - Jan Zumwalt
30/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 30 of 45
A complete list of all the operators for expras well as a definition of regular
expressions is given in Appendix B. One interesting operator for string operations
is the colon (:). It is used to match characters in the first operand against a
regular expression specified in the second operand. The only difference between
the regular expressions used by ed and those used by expris that expranchors all
searches to the beginning of the string. This means that is not a special
character with expr.
The : operator of expr normally returns the number of characters successfully
matched; 0 if no characters match. Using this return value and the general match
anything pattern. .*. the following shell script will return the number of
characters in a string:
#len length of a stringexpr $1, : . *
One final note. expr receives arguments after they have been processed by the
shell. Therefore, if a shell variable contains a string that looks like one of
exprs operators. expr ill become confused. For example, the following would
confuse expr:
x=
expr $x = =
This is because, after shell substitution, the command to exprlooks like
expr = = =
The solution is to precede the operands with some character that does not have a
special meaning. For example.
expr Z$x = Z=
will form the same comparison as the earlier example but will not fail because of
the special meaning of the = character.
Falsefalse ;Return unsuccessful Exit Status
True
true ;Return successful Exit Status
Go Function
The following shell function is a replacement for the cd command. By using go
instead of cd your prompt string will be set to the last part of the pathname of
your current directory.
go()
cd $1PS1= pwd
PS1=basenarne $PS1` >
You use it just like cd. For example. to change to directory /usr/me/junk von
enter
go /usr/me/ junk
Your prompt would then be set to junk>.
8/14/2019 Bash Shell Referance - Jan Zumwalt
31/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 31 of 45
redoThe following shell function will repeat the specified command forever at the
specified interval. Useful for running, a process status every 10 minutes. It
clears the screen before each execution.
redo () {
clscr=tput clear
wtime=$l save wait timeshift # shift out wait timewhile true # do foreverdo
echo $clscr clear screen$* # execute command
sleep $wtimedone
The parameters to redo are the W ait time and the command line to execute
repeatedly. For example. to run a ps -ef command every 10 minutes (6(X) seconds),
enter:
redo 600 ps -ef
Assigning the output from the tput command to clscr means that it only needs to be
executed once. The wait time is assigned to the shell variable wtime and then it
is shifted out of the command line. Finally. a while loop is executed which echoes
the clear string. executes the command line (referenced by $* and sleeps for the
specified time.
Kill
kill [option]pids ;Terminate or send Signal to processes
option: signo decimal number of signal sent (15 default)
1 hangup
2 interrupt
3 quit4 illegal instruction
5 trace trap6 IOT instruction
7 EMT instruction
8 floating point exception
9 kill
10 bus error
11 segmentation violation
12 bad system call argument
13 write on unread pipe
14 alarm clock
15 software termination signal
16 user defined signal 117 user defined signal 2
Standard BSD signals
Number
SymbolicName
.DescriptionDefault
CanBe
Caught
CanBe
Blocked
Dumps
Core
1 SIGHUP Hangup Terminate Yes Yes No
2 SIGINT Interrupt Terminate Yes Yes No
3 SIGQUIT Quit Terminate Yes Yes Yes4 SIGILL Illegal instruction Terminate Yes Yes Yes5 SIGTRAP Trace trap Terminate Yes Yes Yes
6 SIGIOT lOT trap Terminate Yes Yes Yes
8/14/2019 Bash Shell Referance - Jan Zumwalt
32/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 32 of 45
7 SIGEMT EMT trap Terminate Yes Yes Yes
8 SIGFPE Arithmetic exception Terminate Yes Yes Yes
9 SIGKILL Kill Terminate No No No10 SIGBCS Bus error Terminate Yes Yes Yes11 SIGSEGV Segmentation violation Terminate Yes Yes Yes
12 SIGSYS Bad argument to system call Terminate Yes Yes Yes
13 SIGPIPE Write on a pipe with no reader Terminate Yes Yes No14 SIGALRM Alarm clock Terminate Yes Yes No
15 SIGTERM Software termination signal Terminate Yes Yes No16 SIGURG Urgent socket condition Ignore Yes Yes No17 SIGSTOP Stop Stop No No No
18 SIGTSTP Keyboard stop signal Stop Yes Yes No19 SIGCONT Continue after stop Ignore Yes No No20 SIGCHLD Child status has changed Ignore Yes Yes No
21 SIGTTIN Background read from controlterminal
Stop Yes Yes No
22 SIGTTOU Background write to controlterminal
Stop Yes Yes No
23 SIGIO 10 is possible on a descriptor Ignore Yes Yes No
24 SIGXCPU CPU time limit exceeded Terminate Yes Yes No25 SIGXFSZ File size limit exceeded Terminate Yes Yes No26 SIGVTALR
MVirtual time alarm Terminate Yes Yes No
27 SIGPROF Profiling timer alarm Terminate Yes Yes No28 SIG WINCH Window changed Ignore Yes Yes No
29 SIGLOST Resource lost Terminate Yes Yes Yes
30 SIGUSR1 First user defined signal Terminate Yes Yes No31 SIGUSR2 Second user defined signal Terminate Yes Yes No
pids process id number(s) to receive the signal
0 implies all processes resulting from current login)
Shutdown
shutdown [message]Example -h = halt, now = time
Shutdown h now
Other options inclued r = reboot, -k = kidding (sends kill message but does not shutdown)
Set Command
srcfile=dataset1
Creates (if it didn't exist) a variable named "srcfile" and sets it to the value "dataset1". If thevariable already existed, it is overwritten. Variables are treated as text strings, unless thecontext implies a numeric interpretation. You can make a variable always be treated as anumber. Note there must be no spaces around the "=".
It is possible to export a variable just for the duration of a single command using the syntax:var=value command args
set Display all the variables currently set in the shellunsetsrcfile
Remove the variable "srcfile"
srcfile=
8/14/2019 Bash Shell Referance - Jan Zumwalt
33/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 33 of 45
Give the variable a null value, (not the same as removing it).exportsrcfile
Added srcfile to the list of variables which will be made available to external program throughthe environment. If you don't do this, the variable is local to this shell instance.
exportList all the variables currently being exported - this is the environment which will be passed toexternal programs.
To set a variable option, enter the set command followed by the desired option or
options. For example. to set x
and v. enter:
set -xv
Unsetting options is similar, except on replace the -with a +. For example, to
unset the u and y options. enter:
set +uv
Because the set command can be embedded in a script as well as entered from the
command line. various options can be turned on and off for part of a script. Forexample, if you are having trouble with a shell script, you could add a set -x
command after all of the commands in the script that you know execute properly.
Then you would only get debugging information for the part of the script w here
the error was occurring.
The -f option of set can be used to turn off filename expansion (wildcard
interpretation). The following example implements a simple calculator as a shell
script using expr:
# mathset -f
echo math: enter: num op num"echo "op is --, , *, / or %
echo math > \cread numi op num2
echo $numl $op $num2 = \cexpr $num1 $op $num2
It is saved in a file called math. To use. you enter math and it prompts for the
operator and two operands. It then uses expr to compute and print the result.
If we entered this script without the set -f command. it would work fine until we
entered an expression involving multiplication (the * operator. The * would be
expanded into the list of filenames in the current directory. By setting -f this
expansion is turned off and the script ill work for all operators that are
accepted by expr.
If you need to determine which flags are set, they are saved in the - shellvariable. The command:
echo $-
will display all the set flags.
Testtest expression ;evaluate expression
Expressions:
b file true if file exists and is a block special file
c file true if file exists and is a character special filed file true if file exists and is a directory
f file true if file exists and is a regular file
8/14/2019 Bash Shell Referance - Jan Zumwalt
34/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 34 of 45
g file true if file exists and has set-GID bit set
k file true if file exists and has sticky bit set
n string true if string is of non-zero length
n1eq n2 true if integers n1 and n2equaln1ge n2 true if integer n1 >= and n2
n1gt n2 true if integer n1 > n2n1le n2 true if integer n1
8/14/2019 Bash Shell Referance - Jan Zumwalt
35/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 35 of 45
echo controlD to terminate:
if cat >>$fn ; then
echo append successful"
fi
The message append successful is printed if the cat command returns a true exit
status (in other words, worked successfully).
A more sophisticated example might take advantage of the shell command read and
the command test. read reads one line from standard input and assigns words of
input to variables on the read command line. One word is assigned for each
variable. with any leftover words assigned to the last variable.
The test command evaluates an expression and returns the value true if the
expression is true, false otherwise. These expressions are made by combining
operators, commonly called primitives, with filename and string operands. See the
reference section for a complete list of primitives. Note that there are two ways
to write a test. The following two lines both test to see if the two shell
variables, $1 and $stuff. are identical. They are equivalent and can be used
interchangeably.
test $1 = $stuff[ $1 = $stuff ]
In the following example, the script erm first echoes the passed parameters, asks
for confirmation and then deletes all the files specified in the passed parameters
if the answer to the confirmation request is y.
# erm
echo About to remove:
echo $*
echo Enter y to removeread answerif test $answer = y ; then
rm $*fi
The quotes around $answer act as a placeholder. This handles the case where the
user entered no answer, but instead hit return in response to the read command.
The indenting is cosmetic. An alternative to write this. script is:
# erm version 2echo About to remove: echo $*echo Enter y to remove
read answer
if [ $answer = y ]then rm $*
fi
The differences are the use of [] instead of test and the introduction of then on
the same line as the test.
Using conditionals and test can further modify append to verify that the specified
file even exists before attempt to append to it. The -f primitive of test can be
used to test for the existence of a regular file. The exclamation point (!) is
used to negate the truth value of an expression. The exit shell command is used to
terminate a script. It returns its argument to the script where zero is true and
non-zero is false.
append version 6fn~${1:-${afile:?filename reqd}}
if test ! f $fn ; thenecho $fn doesnt exist
exit 1fi
8/14/2019 Bash Shell Referance - Jan Zumwalt
36/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 36 of 45
echo "appending to $fn
echo "control-D to terminate:
if cat >> $fn
thenecho append successful
fi
The full form of the if statement is as follows (where [] are used to indicate
optional expressions):
if cmdlthencmd2
[elif cmd3 then cmd4]...[else cmdsn]
fi
Using this form of the if statement, we can add a message in response to a request
to not continue with the remove.
# erm version 3
echo About to remove:
echo $*echo Enter y to remove files
read answerif [ $answer = y ] ; then
rm $*else
echo remove aborted
fi
While StatementThe while command repeatedly executes a command and each time the execution
returns a true exit status a second set of commands is executed. The while command
takes the following form:
while cmd1do
cmd2done
As long as the execution of cmd1 returns a true exit status, cmd2 is repeatedly
executed. A simple way to use while is creating a loop that will be executed
forever. In the following example, a process status (ps) command is executed every
60 seconds. The tput command clears the screen before each execution of ps.
while sleep 60
dotput clear
ps -adone
Another example uses while and the built-in shell shift command to print the
arguments to a command. The following script prints the arguments passed to it.
# printargecho $0 called with $# arguments
echo They are:
while [ $# gt 0 ]do
echo $1shift
done
8/14/2019 Bash Shell Referance - Jan Zumwalt
37/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 37 of 45
Until CommandThe until command has exactly the same syntax as the while command. The only
difference is that an until loop is executed as long as the command returns false
rather than true.
The following script will check for the existence of a specified file. It checks
every 60 seconds and once the file exists, it is displayed.# exprintuntil test f $1do
sleep 60done
cat $1
For CommandThe for command can be used to sequentially process a set of strings. It
successively assigns a string to a shell variable from a specified list of strings
and then performs a specified loop. Here is the basic syntax:
forname [in strings ]
docmds
done
Note that the brackets are not part of the command. They indicate that the
contained information is optional. If in strings is not specified, all arguments
to the shell file ($*) are used.
The following shell script takes a list of filenames as arguments and displays
whether they are readable. It uses the -r primitive of test.
# canread
for x ; doif [ r $x ] ; thenecho $x is readable,
elseecho $x cannot be read
fidone
It is possible to generate a set of strings for the for command by executing
another UNIX command. For example. the following script performs the same
readability test but it is performed on files whose names are in a file specified
on the command line. The cat command is used to read this file and supply its
contents to the for command.
# canread2for x in cat $1
do
if test r $x ; thenecho $x is readable
elseecho $x cannot be read
fi
done
Case CommandThe case command selects a set of commands to execute by matching cases to a
control string. If the control string matches a case pattern, the associated
commands are executed.
The form of the case statement is:
case string in
pat!) eomniands1:;
8/14/2019 Bash Shell Referance - Jan Zumwalt
38/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 38 of 45
pat2) (omrnands2;;
esac
string is successively compared to pat1, pat2,... until a match is found. When
there is a match, all commands up to a double semicolon (;;) are executed.
The shell wildcards * and ? can be used in patterns as well as the [] notation for
selection. Also, the I (or) symbol can be used to indicate that if either
expression matches, it is considered a match.
For example, the following commands print a greeting based on the current hour
returned by the date command.
hour=date +%H`case $hour in
0?|1[0l]) echo Good Morning;;l[27]) echo "Good Afternoon;;
18) echo Dinner Time!;;*) echo Good Evening;;
esac
Note that the * pattern is used as the alternative if all else fails. As it willmatch anything. If used, it must appear as the last choice.
Shell Functions
Starting with System 5. Release 2. shell functions have been available. A shell
function is an alternative to placing shell commands in a file to make a shell
script.
Functions vs. ScriptsThe biggest advantage of shell functions over shell scripts is fast execution. As
they are saved in the data area of the current shell, a file sy stem search is notrequired in order to locate and execute them.
On the negative side, shell functions are always local to the shell that defined
them. This means that each shell you create must redefine the functions if it
needs access to them.
Another way shell functions differ from shell scripts is their access to shell
variables. Because a shell function is executed by the current shell whereas a
shell script is executed by a sub-shell, functions have access to all the
variables of the current shell. This means, for example, that a cd command in a
shell function will change your current directory and it will stay changed after
the function has completed execution. A cd command in a shell script is only
effective for the execution life of the script.
Defining a FunctionThe general syntax to define a function is:
func( ){ list;}
where func is the function name and list is a list of shell commands that form the
function definition. Note that a space is required following the opening brace in
the definition. If the closing brace does not appear on the same line as the last
command in list, the semicolon is optional.
The following function looks for matching lines in a file named .fone in your home
directory; and then in /etc/fone. Note that the word $* is a special variable
that means substitute all parameters here but put quotes around the outside of
8/14/2019 Bash Shell Referance - Jan Zumwalt
39/45
NeatInfo.com - by: Jan Zumwalt May 15, 2012BASH SHELL Reference Copyright 2002-2012
Pg 39 of 45
them so they are treated as a single argument to the grep command. This means that
the function will pass multiple words to grep in a single argument which makes
lookups of, for example. John Smith possible.
phone()grep $* $HOME/.fone /etc/fone
The function phone was entered on three lines. Once the first line was entered
(which must include the opening brace ({)) the shell prompted with its secondary
prompt string (> by default) until a matching close brace was encountered. You
could have also entered the function on one line, but if you did. you need to
remember the space following the { and the required before the }.
Where to Define FunctionsIf you enter a function definition from the command line, it will exist for the
life of the current shell. Generally. however, it is desirable to either always
have functions defined or have a set of canned functions that you can define
easily when desired.
You can enter functions that you want always defined into your .profile. This
means that whenever you log on. the definitions will be interpreted.
If you have various sets of functions that may be useful i/o a particular project.
you can include them in files. i.e.. put all related function definitions in one
file. Then you can use the d