Preview only show first 10 pages with watermark. For full document please download

Bash Shell Referance - Jan Zumwalt

A Linux Administrator's quick guide to the most important Bash shell commands and concepts. (45 pages)

   EMBED


Share

Transcript

This and many other develope develope references available available at http:/neatinfo.com/d ev_notes/_cheat-sheets Notes:  __________________________________________________  ______________________ ____________________________________ ________  __________________________________________________  ______________________ ____________________________________ ________  __________________________________________________________  __________________________________________________ ________  __________________________________________________  ______________________ ____________________________________ ________  __________________________________________________  ______________________ ____________________________________ ________  __________________________________________________________  __________________________________________________ ________  __________________________________________________  ______________________ ____________________________________ ________  __________________________________________________  ______________________ ____________________________________ ________  __________________________________________________________  __________________________________________________ ________  __________________________________________________  ______________________ ____________________________________ ________  __________________________________________________  ______________________ ____________________________________ ________  __________________________________________________________  __________________________________________________ ________  __________________________________________________  ______________________ ____________________________________ ________  __________________________________________________  ______________________ ____________________________________ ________  __________________________________________________________  __________________________________________________ ________  __________________________________________________  ______________________ ____________________________________ ________  __________________________________________________  ______________________ ____________________________________ ________  __________________________________________________________  __________________________________________________ ________  __________________________________________________  ______________________ ____________________________________ ________  __________________________________________________  ______________________ ____________________________________ ________  __________________________________________________________  __________________________________________________ ________  __________________________________________________  ______________________ ____________________________________ ________  __________________________________________________  ______________________ ____________________________________ ________  __________________________________________________  ______________________ ____________________________________ ________  __________________________________________________  ______________________ ____________________________________ ________  __________________________________________________________  __________________________________________________ ________  __________________________________________________  ______________________ ____________________________________ ________  __________________________________________________  ______________________ ____________________________________ ________  __________________________________________________________  __________________________________________________ ________  __________________________________________________  ______________________ ____________________________________ ________  __________________________________________________  ______________________ ____________________________________ ________  __________________________________________________  ______________________ ____________________________________ ________  __________________________________________________________  __________________________________________________ ________  __________________________________________________  ______________________ ____________________________________ ________ NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference Pg 2 of 45 May 15, 2012 Copyright © 2002-2012 Table of Contents Table of Contents ...........................................3 Commands & Programs Programs - Alphabetica Alphabeticall ......... 4 The Environmen Environmentt .......................................... 21 Exported varia Exported variables bles ............................... ........... 21 Common shell varia variables bles .................... .............. 21 Regularr Expre Regula Expressions ssions ......................... .............. 21 Langauages Langa uages ......................... ........................ .... 4 Commands & Programs - by Function ............5 Archives ...................... ......................... ............ 5 Archives Communication Communi cation & Network ............................... 5 Edit & View ........................ ...................... ......... 5 File & Dir Manage Management ment ......................... ............ 5 Languages Langu ages ........................ ...................... ......... 5 Office Utilities Utilities ...................... .......................... ... 5 Printer .............................................................. 5 Process Proce ss Manag Management ement...................... ................. 6 Search Searc h and Patterns..................... .................... 6 System Administration Administration ..................... ................. 6 Wild Cards ................................................... 22 Wild Strings ...................................... .............. 22 Wild Chara Character cter .................... ......................... ... 22 Match Lists ................................. .................... 22 Quoting ........................................................ 23 Single Quotes ..................... ......................... ... 23 23 Double Quotes .................... ......................... ... 23 Single Character Escape .......................... ...... 23 I/O Redirection ............................................. 24 Output Redire Redirection ction ...................... .................... 24 Input Redir Redirection ection....................... ...................... 25 Here Docume Documents nts ....................... ...................... 25 Pipes — Connec Connecting ting Commands ......... ........... 26 Basic Directory Structure ................................ ................................ 7 Common Backup Directories Directories ............................ 7 Log files ........................................................... 7 Spool files ........................................................ 7 Configuration Config uration files ......................... .................... 8 Device files........................ ...................... ......... 8 Other Important files ..................... .................... 9 X Window files..................... ......................... .... 9 Unix Commands........................................... 27 Search Order ...................... ......................... ... 27 Chmod Command..................... ...................... 27 Echo ..................... ....................... ................... 27 Expr ......................... ......................... .............. 28 False ........................................ ...................... 30 True ......................... ......................... .............. 30 Go Functi Function on ..................... ......................... ...... 30 redo ......................... ......................... .............. 31 Kill ............................................ ...................... 31 Shutdown ......................................... .............. 32 32 Set Comman Command d ..................... ......................... ... 32 Test ......................... ......................... .............. 33 Trap Comman Command d ......................... ...................... 34 Special Characters ....................................... 10 Input/Output Input/Outp ut.................................................. 10 Preset Shell Parameters............................... 10 10 Login environment environment ........................ .................. 11 Shell internal internal settings ..................................... 11 Process Proce ss ID variables....................................... 12 ksh/bash ksh/bas h additi additional onal features ........................... 12 Bash Shell Concepts C oncepts .................................... 13 Syntax......................... ......................... .......... 13 Bash Startup & Kill ........................................ 13 Configuration Files Configuration Files .............. .......................... . 13 Invoking Invokin g Shell ...................... .......................... . 14 ‘dot’ Command Command ..................... ........................ .. 14 XWindow & KDE Startup ...................... .......... 15 Background Backg round Proce Processing ssing........................ .......... 15 Terminating Termina ting a Proce Process ss..................... ............... 15 Environment Enviro nment ......................... ........................ .. 15 Conditionall Statements ................................ 34 Conditiona If Statement ...................................... .............. 34 While Statement ............................... .............. 36 Until Command ............................................ ... 37 For Command..................... ......................... ... 37 Case Comman Command d ........................ ...................... 37 Shell Functions............................................. 38 Functions vs. Scrip Functions Scripts ts ......................... .............. 38 Defining Definin g a Functi Function on ..................... .................... 38 Where to Define Functions........................ ...... 39 Status of Defini Definitions tions ..................... ................... 39 Built-in Shell Commands .............................. 17 Parameters & Variables................................ 18 18 Assigning a Varia Assigning Variable ble ..................... .................. 18 Referencing Refere ncing a Variab Variable le ................................... 18 Speciall Variables....................... Specia Variables....................... ..................... 18 Position Positio n Parameters ..................... .................. 19 Shift Command Command .................................... .......... 19 Set Command ..................... ......................... .. 19 Conditional Conditio nal Use of Varia Variables........................... bles........................... 20 NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference Search Order................................................ 39 Command Line Shell Invoking...................... 40 Invoking Invokin g ...................................... .................... 40 Debugging.................................................... 41 Linux Bash Command Reference Sheet....... 42 Pg 3 of 45 May 15, 2012 Copyright © 2002-2012 Commands & Programs - Alphabetical adduser awk at  bc cal calendar cancel cat cd chgrp chmod chown cmask cmp comm  compress cp cpio cron cu cut date dd df diff du echo emacs env ex eqn find finger fork fsck ftp grep gzip head history info join kill less ln login lp lpc lprm  lpstat lpq ls  mail  mailx  man  mesg  mkdir  mm   more manage user account search & editing job scheduler calculator calendar reminder service remove print jobs from queue concatenates or prints files change directory change group permissions change file/dir permissions change owner permissions sys def permission – see umask compare two text files find same lines of sorted files compress file copy files file archive program job scheduler call another system cut/paste columns of text date and time file copy program mounted file sys/drives info difference between two files file & dir disk usage shows argument editor show environment variables line-oriented text editor format mathematical text find and act on files user info create child process file system check and fix file transfer search pattern and do action compress files show first lines of file print last commands like man, command info join two columns of text terminate or send signals file viewer create file links sign on to system line printer manager manage print jobs remove print jobs status of print jobs status of print jobs show directory contents manage mail advanced mail management manual of command info permit or deny talk messages create new directory macro print formatter file viewer, use less instead NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference  mount  mv  ping netstat nroff  passwd  paste  pg  ping  postnews  pr  ps  pstat  pwd rcp readnews rlogin rm  rn rmdir rpm  script sed shl sort spell shutdown split stty tbl tail talk tar tee telnet time troff umask umount uncompress uniq uptime uucp uupick uuto vi wc who write zcat init make file sys or device move or rename files transfer time & route transfer info print formatter, use mm instead change login password cut and paste columns of text file viewer, use less instead transfer time & route netnews writer format and print text file show program status show kernel info print working directory remotely copy files netnews manager remote login remove files netnews manager remove directories manage packages saves bash session to file pattern editor shell manager ort and merge text files spelling checker halt or reboot system text editing set terminal options put tables into documents view last lines of text file talk (type) to another user combine files split output net file manager time info typeset formatting usr default perm – see cmask remove file system or device expand compressed file remove dup lines of text file elapsed time since boot file transfer between systems retrieve file sent via uuto Send file to another system text editor word count who is logged into system write to another user display compressed file Langauages cc f77  make nasm   pc  perl Pg 4 of 45 c compiler fortran compiler source code manager assembler pascal compiler perl compiler May 15, 2012 Copyright © 2002-2012 Commands & Programs - by Function Archives compress cpio gzip rpm  tar uncompress zcat compress file file archive program compress files manage packages combine files expand compressed file display compressed file Communication & Network cu ftp getty netstat  ping  pty tty rcp rlogin rset stty talk tee telnet termcap tset uucp uupick uuto call another system net file manager transfer info transfer time & route remotely copy files remote login set terminal options talk (type) to another user split output net file manager file transfer between systems retrieve file sent via uuto Send file to another system Edit & View awk cat cmp comm  cut diff echo emacs eqn ex head join less  more nroff  paste  pg sed sort split tail tbl uniq vi search, filter, edit concatenates or prints files compare two text files find same lines of sorted files cut & paste columns of text difference between two files show argument(s) editor format mathematical text line-oriented text editor show first lines of file join two columns of text file viewer file viewer, use less instead prt formatter, use mm instead cut and paste columns of text file viewer, use less instead search, filter, edit sort and merge text files txt edit view last lines of text file put tables into documents remove duplicate lines text editor File & Dir Management cd chgrp chmod chown change change change change directory group permissions file/dir permissions owner permissions NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference cp dd df du find fsck grep ftp ln ls  mkdir  mount  mv  path  pwd rm  rmdir umount uucp uupick uuto copy files file copy program mounted file sys & drive info file & dir disk usage find and act on files file system check and fix search pat and act on file file transfer create file links show directory contents create new directory make file or dev available move or rename files change shell environment print working directory remove files remove directories remove file system or device file transfer between systems retrieve file sent via uuto Send file to another system Languages cc f77 gcc java  make nasm   pc  perl tk tkl c compiler fortran compiler gcc compiler java compiler source code manager assembler pascal compiler perl compiler tk compiler tkl compiler Office Utilities  bc cal calendar date  mail  mailx  postnews readnews rn spell talk time wc who write calculator calendar reminder service date and time mail managment advanced mail management netnews writer netnews mgr, use rn instead netnews manager spelling checker talk (type) to another user time info word count who is logged into system write to another user Printer cancel lp lpc lprm  lpstat lpq  mm  nroff  pr troff Pg 5 of 45 remove print jobs from queue line printer manager manage print jobs remove print jobs status of print jobs status of print jobs macro print formatter prt formatter, use mm instead format and print text file typeset formatting May 15, 2012 Copyright © 2002-2012 Process Management at cron date env export fork kill  ps tee job scheduler job scheduler date and time show environment variables send variable to shell create child process terminate or send signal program status split output Search and Patterns awk find grep sed sort nohup  ps tee pattern scanning find and act on files search pat and act on file pattern editor sort and merge text files prog running after logoff program status split output System Administration adduser chgrp chmod chown manage change change change user account group permissions file/dir permissions owner permissions NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference cmask date echo env find finger grep history info login  mail  mailx  man  mesg  passwd  path  pstat script shl shutdown stty time umount umask uptime who Pg 6 of 45 sys default perm – see umask date and time shows argument show environment variables find and act on files user info search pattern & do actions show command history like man, command info sign on to system manage mail advanced mail management manual of command info permit or deny talk messages change login password change shell environment show kernel info saves bash session to file shell manager halt or reboot system set terminal options time info remove file system or device usr default perm – see cmask elapsed time since boot who is logged into system May 15, 2012 Copyright © 2002-2012 Basic Directory Structure / ...................... ........... /bin .................... ........... /boot ................... ........... /dev .................... ........... /etc .................... ........... /home ................... ........... /lib .................... ........... /lost+found ..................... ... /mnt .................... ........... /opt .................... ........... /proc ................... ........... /root ..................... ........ /sbin ................... ........... /tmp .................... ........... /usr .................... ........... /usr/bin ................... ........ /usr/doc ................... ........ /usr/man ................... ........ /usr/include ....................... /usr/include/g++ ................... /usr/lib ................... ........ /usr/local ...................... ... /usr/sbin ....................... ... /usr/src ................... ........ /usr/src/linux ..................... /usr/tmp ................... ........ /var .................... ........... /var/tmp ................... ........ ;root directory ;system commands ;kernel & boot files ;device drivers ;pub system configuration files ;user private files & settings s ettings ;c compiler libraries ;files fragments are saved s aved here ;external file systems and devices d evices ;optional programs, i.e. KDE ;process files ;root’s custom files & settings settings ;superuser commands needed to start ;system temporary files ;pub cmds & prop, can be b e read-on ly ;pub commands ;pub info files ;pub man files ;pub c header files ;pub c++ header files ;pub libraries ;extensions independent of distro ;superuser commands ;pub application source files ;kernel source files ;pub temporary files ;config files, link to /usr ;pub temporary files Common Backup Directories /etc/lilo.conf ..................... /boot/grub ...................... ... /etc/fstab ...................... ... /etc/modules.conf .................. /etc/isapnp.conf ................... /etc/Xll/XF86Config -4 .............. /etc/X11/XF86Config ................ /etc/cups ....................... ... /etc/printcap ..................... /etc/bashrc ..................... ... /etc/profile ....................... /etc/crontab ....................... /etc/rc.d ....................... ... /etc/inittab ....................... /etc/ssh ................... ........ /root ..................... ........ /home ................... ........... ;Lilo’s boot loader configuration ;grub’s boot loader configuration ;disk partition table configuration ;modules to load l oad % their parameters ;ISA Plug & Play hardware parameters ;X’s settings X’s settings ;CUPS’s printer settings ;lpr print settings ;bash shell system-wide configuration ;system-wide environment ;cron jobs to be executed ;run level settings ;sets default d efault run level le vel & settings ;ssh settings for secure se cure remote rem ote access acc ess ;root’s custom files & settings settings ;user’s custom files & settings Log files /var/log ;log files Spool files /usr/spool /usr/spool/lp NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference ;buffer for file xfer, etc ;buffer for printer Pg 7 of 45 May 15, 2012 Copyright © 2002-2012 Configuration files /boot/grub ...................... ... /etc/bashrc ..................... ... /etc/crontab ....................... /etc/cups ....................... ... /etc/DIR_COLORS .................... /etc/fstab ...................... ... /etc/group ..................... ... /etc/hosts ..................... ... /etc/initd.conf ................... /etc/inittab ....................... /etc/isapnp.conf ................... /etc/lilo.conf ..................... /etc/modules.conf .................. /etc/passwd ....................... /etc/printcap ..................... /etc/profile ....................... /etc/rc.config ..................... /etc/rc.d ....................... ... /etc/shadow ....................... /etc/ssh ................... ........ /etc/syslogd.conf ................. /etc/XF86Config .................... /etc/X11/XF86Config ................ ~/home/.profile .................... /sbin/init.d ....................... ;grub’s boot loader configuration ;bash shell system-wide configuration ;cron jobs to be executed ;CUPS’s printer settings ;ls c olor settings ;disk partition table configuration ;user groups ;hostname to address table ;net services, ftp, telnet, etc ;sets default d efault run level le vel & settings ;ISA Plug & Play hardware parameters ;lilo’s boot loader configuration ;modules to load l oad & their parameters ;usr info, shell pref, home dir, etc ;lpr print settings ;shells login script ;sys config s ettings r ead during du ring boot bo ot ;run level settings ;passwords ;ssh settings for secure se cure remote rem ote access acc ess ;syslog daemon settings ;X wi ndow settings ;X’s settings ;usr custom environment settings ;scripts for system start Device files /dev/fd0–fd1 . .................... ................... ... /dev/hda ................... ........ /dev/hda1–hda15 .................... /dev/hdb ................... ........ /dev/hdb1–hdb15 .................... /dev/sda ................... ........ /dev/sda1–sda15 .................... /dev/sdb ................... ........ /dev/sdb1–sdb15 .................... /dev/sdc... ..................... ... /dev/cdrom ...................... ... /dev/hda - hdd ..................... /dev/scd0 – scd1 s cd1 ................... /dev/rmt0 ....................... ... /dev/nrmt0 ...................... ... /dev/ftape ...................... ... /dev/ntape ...................... ... /dev/mouse ...................... ... /dev/atibm ...................... ... /dev/logibm ..................... ... /dev/inportbm ................... ... /dev/modem ...................... ... /dev/ttS0–ttS3 ..................... /dev/cua0–cua3 ..................... /dev/lp0–lp2 ....................... /dev/tty1–tty8 ..................... /dev/null ....................... ... /dev/zero ....................... ... NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference ;floppy ;1st IDE & CDROM drive ;1st IDE & CDROM drive partitions ;2nd IDE & CDROM drive ;2nd IDE & CDROM drive partitions ;1st SCSI & USB drive ;1st SCSI & USB drive partitions ;2nd SCSI & USB drive ;2nd SCSI & USB drive partitions ;3rd SCSI & USB drive... ;cdrom drive, linked to driver ;ATAPI IDE cdrom drive ;SCSI cdrom drive ;1st SCSI tape, auto rewinds ;1st SCSI tape, no auto rewind ;1st floppy tape, auto rewinds ;1st floppy tape, no auto rewind ;mouse ;ati graphics card mouse ;logitech mouse ;ps/2 bus mouse ;link to t o com port with wi th modem ;serial port ;serial port ;parallel port ;virtual seri al console ;null device ;output endless null bytes Pg 8 of 45 May 15, 2012 Copyright © 2002-2012 Other Important files /usr/linux ...................... ... /etc/skel ....................... ... /”home”/ ................... ........ .profle .................... ........ .bashrc .................... ........ .exrc ................... ........... .xinitrc ................... ........ .fvwmrc .................... ........ .ctwmrc .................... ........ .openwin-menu ................... ... ;kernel source ;new user use r skeleton files cop ied to users user personal and setup files usr login script usr bash config usr vi config usr x win startup fvwm win mgr startup ctwm win mgr startup olvwm win mgr startup X Window files Coming soon ..................... ... kernel source NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference Pg 9 of 45 May 15, 2012 Copyright © 2002-2012 Special Characters | ; & && || ‘ “ \ ? * [chars] [!chars ] 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 match any of chars (pair separated by a — matches a range) match any except chars in-line command execution Input/Output All of these operators may be preceded by an optional file descriptor. Defaults are shown in parentheses. < file > file >> file <&n >&n <&- >&<< word  <<- word  use file as stdin use file as stdout like > but append to file if it exists duplicate input file descriptor from n (stdin) duplicate output file desc. from n (stdout) close stdin close stdout treat line with word as EOF on input If any of word is quoted, no additional processing input by shell. Otherwise: parameter & command substitution occurs  escaped newlines are ignored  a \ must be used to quote \, $,  as above with leading tabs ignored is done on Preset Shell Parameters Several special variables are used by the system -- you can use these, but may not be able to change them. The special variables use uppercase names, or punctuation characters. Some variables are set by the login process and inherited by the shell (e.g. $USER  ), while others are used only by the shell. These ), are some of the more commonly used ones: 1 2 3 $n $* $@ “$*“ “$@“ $# default input default output default error use positional parameter n all positional parameters all positional parameters equivalent to “$1 $2 ...“ equivalent to “$1” “$2”... number of positional parameters There are various ways to conditionally use a variable in a command. ${datafile-default} Substitute the value of $datafile, if it has been defined, otherwise use the string "default". This is an easy way to allow for optional variables, and have sensible defaults if they haven't been set. If datafile was undefined, it remains so. NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference Pg 10 of 45 May 15, 2012 Copyright © 2002-2012 ${datafile=default} Similar to the above, except if datafile 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 no sensible default value to use. $name $name: ${var  } ${var   —  text text} ${var  =text} ${var  ?text} ${var  +text} only checks if name is set checks if name is set and non-NULL use braces to delimit shell variable name use var if set, else use word use var if set, also set name to word use var if set, otherwise print word and exit use word if var set, otherwise use nothing Example ${datafile?"error message"} debug message if var is not set Login environment $EDITOR  $USER  $LOGNAME $PATH $TERM  $PAGER  $SHELL $CDPATH $HOME $IFS $MAIL $MAILCHECK $MAILPATH $PS1 $PS2 $SHACCT name =word  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 to start up this program instead of some built-in default (e.g. "crontab -e". This also determines the default command-line-editing behavior in interactive shells. currently logged-in username Preset to the. The list of directories that will be searched for external commands. You can change this in a script to make sure you get the programs you intend, and don't accidentally get other versions which might have been installed. 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 to send to achieve special effects. If set, this contains the name of the program which the user prefers to use for text file viewing. Usually set to "more" or "less" or something similar. Many programs which  man). 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 need to page output to the user. name of default shell search path for cd command home directory for cd command field separators (space, tab. newline) name of a mail file, if any check for mail every n seconds fnames to check new mail (: separator; %message) primary prompt string ($) secondary prompt string (>) accounting file for user shell procedures set name to specified word fname may be followed by Shell internal settings 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. $PWD NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference Pg 11 of 45 May 15, 2012 Copyright © 2002-2012 $$IFS Option flags of current shell command. Internal Field Separators: the set of characters (normally space and tab) which are used to parse a command line into separate arguments. This may be set by the user for special purposes, but things 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 how the script was called. $! (readonly) Process ID of the last command started in background. $$ ksh/bash additional features (readonly) Integer number of seconds since this shell was started. Can be used for timing commands. $SECONDS $RANDOM  Every time it is valuated, $RANDOM returns a random integer in the range 0-32k. RANDOM may be set to "seed" the random number generator. $LINENO (readonly) Always evaluates to the current line number of the script being executed - useful for debugging. NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference Pg 12 of 45 May 15, 2012 Copyright © 2002-2012 Bash Shell Concepts Syntax This 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 substituted  for things such as filenames. Note that if an italicized word is plural (i.e. files ), multiple arguments are files), 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 — list — n — name — oct —  pat — word — or fname : a filename, pathname, or variable of one fname: one or more  pipelines  pipelines that can be separated by ;, &, &&, || and optionally be terminated by ; or &. an integer the name of a shell variable an octal number explained in conjunction with the case command. 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 in the user’s 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 1. 2. 3. 4. /etc/profile $HOME/.bash_profile $HOME/.bash_login $HOME/profile Non-Login Shell 1. $HOME/bash.rc usually points to -> 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 NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference Pg 13 of 45 May 15, 2012 Copyright © 2002-2012 ~./bash_profile that contains a script that automatically executes the commands placed 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 superuser  status 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 commands contained 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 Shell This 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: mark modified export variables  —a  —c cmd execute cmd, default reads cmds from file in first entry of args. if non-interactive, exit if a command fails  —e disable wildcarding  —f  —h locate and remember functions on definition instead of on execution set interactive mode  —i all keyword arguments placed in environment  —k read commands without executing them  —n  —r set restricted mode read commands from stdin  —s read and execute one command, then exit  —t  —u set error upon substituting an unset variable print input lines as read  —v print commands and arguments as executed  —x 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. NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference Pg 14 of 45 May 15, 2012 Copyright © 2002-2012 XWindow & KDE Startup For completeness the xwin startup is briefly discussed here. The xwindow system should always be started using the startx command which is designed to get things going. A tremendous amount of  programs and synchronization is needed for the GUI to successfully load. startx <- shell command command calls xinit command command which must have things setup for it xinit shell command calls the following config files in order $HOME/.Xresources <- usually exist $HOME/.Xmodmap <- usually exist $HOME/.xinit <- does not usually exist $HOME/.Xclients <- does not usually exist /etc/X11/xinit/xinitrc /etc/X11/xinit/Xclients KDE users have a nice directory (folder) where the entire contents will be run, this is similar to MS Window’s startup folder. $HOME/.kde/Autostart Background Processing Instead of running a command interactively, it can be run in the background. This means that the command will continue to run but you will immediately get your prompt back so that you can continue with interactive use of your terminal. To start a command in the background. append an ampersand & to the end of the command line. You may want to redirect the output so that it doesn’t interfere with what you are doing. For example, to find all the tiles named .core in the /usr directory and save their names in a file, use the command... find /u -name .core -print > temp & Find would run and you could check to see if it was complete by using command. The file temp would grow as it received output from the command. the ps When a command is started in the background, the shell establishes a slightly different environment for it. The stdin of the command is connected to /dev/null instead of /dev/tty. This means that if the command reads any input from standard input, it will get an end of file (EOF). Also, the interrupt and quit signals are disabled. This means that if you interrupt an interactive program while you have a background job running, the background job will not be affected. The hangup signal, however, is sent to the job. If you intend to have your background job continue even if you log out, you should precede the command with the nohup command. This tells the shell not to send the hangup signal to the command. For example, to run find as described above and have it ignore the hangup signal... nohup find /u -name .core -print > temp & Terminating a Process The kill command can be use to terminate any process. It can send any one of many different signals. Don’t confuse the kill process command with the computer s hutdown commands. halt poweroff  reboot shutdown Environment When you first login many defaults are setup. Two examples are your home directory $HOME and a default search path $PATH for commands. It is possible to alter these defaults by creating a file called .profile in your home directory  and placing the NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference Pg 15 of 45 May 15, 2012 Copyright © 2002-2012 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 exported  to 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 CDPATH PATH=$HOME/bin:/bin:/usr/bin:. CDPATH=:$HQME:/usr/local PS1=”Hi Phil >“ TERM=h19 umask 027 news –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. NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference Pg 16 of 45 May 15, 2012 Copyright © 2002-2012 Built-in Shell Commands # .file : [  break [n] cd [file] continue [n] echo [words] eval [words] exit [words] exit [n] export [names] getopts hash [—r] [files] start of comment: terminated by a newline read and execute commands from file null command: returns 0 exit status see test exit from enclosing for or while loop change current directory to file do next iteration of enclosing for or while echo words (see echo in Appx. B) evaluate words and execute result execute words in place of shell exit with return value n export names to environment of commands parse parameters and options remember locations of f iles; with no files s hows hash info —r forgets all remembered locations same as exec newgrp words newgrp [words] print working directory name  pwd read names read stdin and assign to names readonly [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 (aefhkntuvxare valid). words set positional parameters set [+options] [words] unset flags rename positional parameters; $n+1 =$1... (n defaults to 1) shift [n] evaluate conditional expressions test print accumulated process times times trap [word][sigs] execute word if signal in sigs received no 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 show how shell would interpret each file type files 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 set file creation permissions mask (see chmod) umask [oct] unset variables or functions names unset [names] wait [n] wait for process n; if no n, wait for all children NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference Pg 17 of 45 May 15, 2012 Copyright © 2002-2012 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 expr command. Assigning a Variable In 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 interpretation of the special meaning of the space character statement. just prevent the in the assignment Referencing a Variable To 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 braces {} to delimit the variable name. with echo Eat ${meal}and milk. other characters, you can use ;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 command ps -ef Special Variables There are built in variables too. For example, $PS1 is your primary shell prompt string (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  NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference Pg 18 of 45 May 15, 2012 Copyright © 2002-2012 The set command displays the values of all shell variables (and shell functions). Position Parameters When 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  positional parameters. parameters. These parameters are referenced in the same manner as shell variables. Description Variable --------------------------------------------number of positional parameters $# command name that invoked script $0 1st parameter $1 2nd parameter $2 etc... For example, the following command... ls –l * Would have the following parameters, Description Variable Value ------------------------------------------------------------------number of positional parameters $# 2 command 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. merely named passed parameters, commonly called keyword parameters. They are Shift Command Shift 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 Command The • • • 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 NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference Pg 19 of 45 May 15, 2012 Copyright © 2002-2012 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 Variables Sometimes 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  } ${var  := :=word  } ${var  :? :?word  } ${var  :+ :+word  } Substitute value of set and non-null; otherwise var  if substitute 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. Use value of var  if set and non-null. Otherwise, print word  and exit from the shell, If word  is omitted, parameter null or not set is printed. 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 2 echo “control—D 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 doesn’t tail. # append version 3 fn=${1:?”filename required”} echo “control—D to terminate:” cat >>$fn NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference Pg 20 of 45 May 15, 2012 Copyright © 2002-2012 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 exported  environment variables of the parent. By default, environment variables are not exported. 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 shell TERM 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 4 fn=${1:—${afile:?”filename req’d”}} echo “appending to $fn” echo “control-D to terminate:” cat >> $fn Regular Expressions Note: multiple re’s may be concatenated c the character c character c (for special characters) \c any character except a newline . any one character in str ( [a-b] means all in range a thru b) [str] NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference Pg 21 of 45 May 15, 2012 Copyright © 2002-2012 [^str] re* re\{m,n\} \(re\) \n ^ $ & % any character except newline or one from str 0 or more occurrences of 1 character re m thru n occurrences of 1 character re group re for later reference 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 Cards Wild Strings The 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 Character Single 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 Lists A third kind of wildcard is a match list. The syntax is [ list] here list is the list 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 rm  command in conjunction with wildcards. If you are not sure what files will be effected, you can use the echo command to test the pattern. NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference Pg 22 of 45 May 15, 2012 Copyright © 2002-2012 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 Quotes The 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 Quotes The 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 Escape The special meaning of a single character can be escaped by preceding it with a backslash \. echo can\’t will print can’t . Double quotes could have been used here but there will be times when the escape character will be the only answer. echo “don’t” 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 interpretation of its special meaning. 2) In the second line, echo prints *, the value of the shell variable me is an asterisk. 3) The third echo lists all files. The shell first substitutes $xy to it’s value 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. Backquote The 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` NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference Pg 23 of 45 May 15, 2012 Copyright © 2002-2012 I/O Redirection Note that in redirection, no filename expansion takes place. Therefore, occurrence of shell meta characters such as * or * or ? is treated literally. any 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 output stderr 2 standard error, default error messages Output Redirection Both stdout and stderr  can 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 following command: 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 > sample date > 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 > stats  ps —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 the  pr 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 all. log 2>&l NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference Pg 24 of 45 May 15, 2012 Copyright © 2002-2012 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 the  ps 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 the terminal: ;prints stdout message “1,2,3 test” echo “1,2,3 test” ;change stdout to a file exec > myout ;commands now sent to file “myout”  ps who echo “temporary redirect” > /dev/tty date exec >/dev/tty echo “back to normal” ;echo “temporary redirect” ;date is sent to file “myout” ;stdout set back to terminal ;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 Redirection Many 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 basically the 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/passwd wc tmp.file NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference Pg 26 of 45 May 15, 2012 Copyright © 2002-2012 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. In fact, 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 isn’t 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 the shell 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 permissions u user access permissions + add the permission to status of files  —  remove the permission from status of files = set the permission of files to specified value r 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 set group ID on execution 2000 set sticky bit (leave program in memory as long as possible) 1000 0X  00 00 owner permission, X added 04 (read), 02 (write), 01 (execute) group permission, X added 04 (read), 02 (write), 01 (execute) 00X  0 other permission, X added 04 (read), 02 (write), 01 (execute) 000X  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 NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference Pg 27 of 45 May 15, 2012 Copyright © 2002-2012 \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: returns expr1 if neither null nor 0; else expr2 expr1 \| expr2 returns expr1 if neither expr  is null or 0; 0 otherwise expr1 \& expr2 returns result of integer compare if both args are ints; expr1 cmpop expr2 otherwise, returns result of lexical compare cmpop is: equal \> greater than = greater or equal >= \< less than less or equal \<= not equal != expr1 mathop expr2 returns result of integer arithmetic on expr  mathop is: addition + subtraction multiplication * division / remainder % expr: re compare expr  with regular expression re search always anchored to beginning of line (^ not special) returns number of chars matched (0 = fail) \(...\) can be used to return portion of expr  The eval command is used to force the shell to rescan a command line and execute the result. If you have constructed a command line from shell variables and passed parameters. it may be necessary to rescan it in order to get the intended meaning. Another way of understanding the action of eval is to consider what the shell would do with your command line after substitution took place. For example, if one of the substituted values had the $ character in it, the shell would interpret this as a reference to a shell variable and it would attempt a substitution. This capability of eval allows you the equivalent of indirect addressing. using the contents of a variable as the address of data rather than the actual data. In the following example, the script etest, the string $data is assigned to shell variable ptr. The single quotes are necessary to prevent the interpretation of the $. Next, the string this is it is assigned to shell variable data. The first two echo commands display the values of ptr and data to verify the assertions above. Finally the eval command line evaluates all its arguments and prints the result, This means that $ptr is interpreted and is replaced by its value $data. Then the echo command embedded in the eval command is executed. After the rescan, this echo becomes echo $data and the printed result is this is it. * etest  ptr=’ $data’ data=”:his data=”:h is is it’ echo ptr is .$ptr. echo data is .$data. eval echo $ptr Unix shell variables contain character strings. The shell itself has no concept of arithmetic operations. For example, the following command sequence x=5 x=$x+$x echo $x NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference Pg 28 of 45 May 15, 2012 Copyright © 2002-2012 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 expr 5 '*/ 3 #use\ # 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_pg count=0 while line do count=’expr $count + 1’ if [ $count —eq 20 ] ; then read stuff You use enter it just like cd. For example. to change to directory /usr/me/junk von go /usr/me/ junk Your prompt would then be set to junk>. NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference Pg 30 of 45 May 15, 2012 Copyright © 2002-2012 redo The following shell function will repeat the specified command specified interval. Useful for running, a process status every clears the screen before each execution. forever at the 10 minutes. It redo () { clscr=’tput clear’ wtime=$l save wait time shift # shift out wait time while true # do forever do echo $clscr clear screen $* # execute command sleep $wtime done 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 option : ;Terminate or send Signal to processes —signo decimal number of signal sent (15 default) 1 hangup 2 interrupt 3 quit 4 illegal instruction 5 trace trap 6 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 1 17 user defined signal 2 Standard BSD signals Numb er 1 2 3 4 5 6 Symbolic Name SIGHUP SIGINT SIGQUIT SIGILL SIGTRAP SIGIOT . Description Default Hangup Interrupt Quit Illegal instruction Trace trap lOT trap NeatInfo.com - by: Jan Zumwalt BASH SHELL Reference Terminate Terminate Terminate Terminate Terminate Terminate Pg 31 of 45 Can Can Dump Be Be s Caug Blocke Core ht d Yes Yes No Yes Yes No Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes May 15, 2012 Copyright © 2002-2012 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 SIGEMT SIGFPE SIGKILL SIGBCS SIGSEGV SIGSYS SIGPIPE SIGALRM SIGTERM SIGURG SIGSTOP SIGTSTP SIGCONT SIGCHLD SIGTTIN 22 SIGTTOU 23 24 25 26 SIGIO SIGXCPU SIGXFSZ SIGVTALR M SIGPROF SIG WINCH SIGLOST SIGUSR1 SIGUSR2 27 28 29 30 31 EMT trap Arithmetic exception Kill Bus error Segmentation violation Bad argument to system call Write on a pipe with no reader Alarm clock Software termination signal Urgent socket condition Stop Keyboard stop signal Continue after stop Child Chi ld status has changed Background read from control terminal Background write to control terminal 10 is possible on a descriptor CPU time limit exceeded File size limit exceeded Virtual time alarm Terminate Terminate Terminate Terminate Terminate Terminate Terminate Terminate Terminate Ignore Stop Stop Ignore Ignore Stop Yes Yes No Yes Yes Yes Yes Yes Yes Yes No Yes Yes Yes Yes Yes Yes No Yes Yes Yes Yes Yes Yes Yes No Yes No Yes Yes Yes Yes No Yes Yes Yes No No No No No No No No No Stop Yes Yes No Ignore Terminate Terminate Terminate Yes Yes Yes Yes Yes Yes Yes Yes No No No No Profiling timer alarm Window changed Resource lost First user defined signal Second user defined signal Terminate Ignore Terminate Terminate Terminate Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes No No Yes No No process id number(s) to receive the signal 0 implies all processes resulting from current login)  pids Shutdown shutdown