Go to the table of contents.
| job control | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
bg→
| disown
| fg
| jobs
| kill
| wait
| suspend
| directory
| cd
| popd
| pushd
| dirs
|
| alias
| unalias
| bind
| break
| case
| command
| continue
| declare
| do
| done
| typeset
| echo
| enable
| eval
| exec
| exit
| export
| fc
| getopts
| hash
| help
| history
| if
| let
| local
| logout
| mapfile
| printf
| pwd
| read
| readarray
| readonly
| select
| shift
| shopt
| source
| test
| times
| time
| trap
| type
| builtin
| ulimit
| umask
| | |||||||||||||||||||
filename in the current shell context. filename does not contain a slash $PATH is searched to locate it.filename, does not need eXexute permission .filename is not found, or cannot be read, the return status is non-zero. ex: 127
alias [-p] [name[=value] …]
The name may contain any valid shell input, including shell metacharacters, execpt =.
The value may contain any valid shell input, including shell metacharacters,
Without arguments or -p, prints the list of aliases on the standard output in a form
that allows them to be reused as input.
alias attrib='chmod' alias bi='vi' alias c='cp -p --interactive' alias cd-='cd -' alias cd..='cd ..' alias cdb='cd www/birding/log' alias chdir='cd' alias ci='vi' alias copy='cp' alias d='dir' |
name=value. alias name alias name=value is displayed.
Aliases allow a string to be substituted for a word when it is used as the first word of a simple command.
The first word of a simple command is replaced by the value of its alias (if unquoted).
The first word of the value is tested for aliases, but a word that is identical to an alias being expanded is not expanded a second time.
Exampe:alias ls="ls -F" works as hoped.
If the last character of value is a [space] or [tab] the next command word is also checked for alias expansion.
Aliases are created and listed with alias , and removed with unalias.
There is no mechanism for using arguments in the replacement text, as in csh.
If arguments are needed, a shell function should be used.
Aliases are not expanded when the shell is not interactive, unless the
expand_aliases shell option is set (see shopt Bash Builtin Commands.
bind [-m keymap] [-lpsvPSV] bind [-m keymap] [-q function] [-u function] [-r keyseq] bind [-m keymap] -f filename bind [-m keymap] keyseq:function-nameDisplay current Readline ( Command Line Editing) key and function bindings, or bind a key sequence to a Readline function or macro. The binding syntax accepted is identical to that of .inputrc (@xref{Readline Init File}), but each binding must be passed as a separate argument: e.g., This is in emacs format where \C-x is control X and \M-x is escape (metakey) x Note: if vi is the command line editor ( set -o vi )
there are a different set of keybindings during the initial input of a line then
when the line has been recalled using [esc]k. Sounds obious since
during initial input when an x is pressed, an x is inserted into the buffer.
Once the line is recalled, vi editing is in effect and x deletes the char under the cursor.
To display the two sets, keyin bind -p then use [esc]k to recall the bind -p command and press enter.
interesting key-bindings which cause problems on various keyboards/telnet clients inclued:
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-v set blink-matching-paren on set byte-oriented off...
-S -s -f filename -q function > bind -q yank yank can be invoked via "\C-y".
-u function -r keyseq
for, while, until, or
select loop.
builtin [shell-builtin [args]]Useful when defining a shell function with the same name as a shell-builtin, retaining the functionality of the builtin within the function.
command [-pVv] command [arguments …]
Runs command with arguments ignoring any
function named command.
Only builtin commands or commands found by searching the PATH are executed.
If there is a function named ls, running command ls within the
function will execute the external command ls instead of calling the function recursively.
-p use a default value for $PATH that is guaranteed to find all of the standard utilities.
The return status in this case is 127 if command cannot be found or an error occurred, and the exit status of command otherwise.
-v display the command or file name used to invoke command to be displayed
-V produces a more verbose description.
In this case, the return status is zero if command is found, and non-zero if not.
> command -v make /usr/bin/make > command -V make make is hashed (/usr/bin/make) > which make /usr/bin/make > which which > command -V which which is aliased to `type -path'
cd | without a directory changes to $HOME. |
cd - | changes to the previous directory. $OLDPWD. |
To have cd use the environment variable specified as directory set the sopt cdable_vars.
For example (perhaps in a .profile): export docs=/home/myname/docs
cd docs changes current working directory to /home/myname/docs
if the current directory was /home/myname/source/
and /home/myhome/source/docs doesn't exist,
To cause bash to correct minor spellings when specifying the new current directory use shopt -s cdspell
If CDPATH exists, it is used as a search path.
If directory begins with a slash,
CDPATH is not used. cd /home/myname/dox /home/myname/dox.-L follow symbolic links, default (see ln)-P Prevent symbolic links from being followed.
for, while, until, or select loop. names are given, the values of variables are displayed.
-p | print attributes and values of each name, additional options are ignored.> declare -p UID declare -ir UID="501" | ||||||||||
-f | function names only are displayed.
> declare -f
update_terminal_cwd ()
{
local SEARCH=' ';
local REPLACE='%20';
local PWD_URL="file://$HOSTNAME${PWD//$SEARCH/$REPLACE}";
printf '\e]7;%s\a' "$PWD_URL"
}
|
+ instead of - to turn off the attribute . local names is not a valid shell variable name
-f foo=bar
-f.
echo [-neE] [arg ...] -n no newline output
-e enable the interpretation of the special character codes.
-E disables the interpretation of the special character codes.
\a | alert (bell) | \b backspace
|
\c | suppress trailing newline | \e escape
|
\f | form feed | \n new line
|
\r | carriage return | \t horizontal tab
|
\v | vertical tab | \\ backslash
|
\nnn the character whose ASCII code is the octal value
nnn (one to three digits) \xnnn the character whose ASCII code is the hexadecimal value
nnn (one to three digits)
\\a …
enable [-n] [-p] [-f filename] [-ads] [name ...]
-n disable builtin shell commands. test : % enable -n test
-p,print, no options or no name arguments : a list of shell builtins . -a list each builtins status. % enable -a" …enable .
enable :
enable [
enable alias
bg bind break builtin caller cd command compgen complete continue declare dirs disown echo enable eval exec exit export false fc fg getopts hash help history jobs kill let local logout popd printf pushd pwd read readonly return set shift shopt source suspend test times trap true type typeset ulimit umask unalias unset wait
-f load the new builtin command name
from shared object filename, on systems that support dynamic loading.
-d delete a builtin loaded with -f.
-s restricts enable to the POSIX special builtins.
If% enable -ps" …
enable .
enable :
enable break
continue eval exec exit export readonly return set shift source times trap unset
-s is used with -f,
the new builtin becomes a special builtin. eval.-c causes command to be executed with an empty (clear) environment. -l as if the login program, the shell passes - as the zeroth arg to command.-a the shell passes name as the zeroth argument to command.
$? Any
parent childscript.sh childscript.sh
RC=$?; if [ $RC -ne 0 ]; then echo " " ++++ RC= $RC;exit $RC ;fi
various commands
exit 4
trap on EXIT is executed before the shell terminates.
See also set
optstring are the option letters to be recognized;
variables used:
If no arguments are given, information about remembered commands is displayed.
Note that if
Not to be confused with the
Write
Read lines from the standard input (or file) into the indexed array variable array, .
Without options displays names and values of variables and functions, sorted according to the
current locale, in a format that may be reused as input. Caution, variable
See also:
Display the list if no options specified:
ex:
The return status is 0.
time a command
see Signals
‡Different linux signals:
example: To remove tmp files and exit with a return code of 9 when the terminal user presses
To make a script "safe" by limiting the execution time and filespace it can use and
For each name, indicate how it would be interpreted if used
as a command name.
A soft limit can be changed up to the maximum set by the hard limit, only root can change resource hard limits.
Once a hard limit has been decreased, it cannot be increased without root privilege
Used as default settings when a new user is added to the system by
The return status is zero unless an invalid option is supplied, a non-numeric argument other than
Examples:
ulimit -f 2
test expr also written as :
Evaluate a conditional expression.
Expressions may be unary or binary†.
String compares are not the same as numeric.
> if [ 01 -eq 1 ]; then echo EQUAL; else echo NO ; fi
> if [ "01" -eq 1 ]; then echo EQUAL; else echo NO ; fi
> if [ 1 ]; then echo TRUE ;fi
Unary expressions are available to test the status of a file.
arithmetic expressions to be evaluated by Evaluation is done in long integers with no check for overflow.
In order of decreasing precedence.
Variables are allowed as operands. Constants with a leading Operators are evaluated in order of precedence. Bash provides one-dimensional array variables. Any variable may be used as an array. Arrays are assigned to using compound assignments of the form where each value is of the form
Elements of an array are referenced using
The directory stack is a list of directories. The directory stack is Special characters used in the prompt :
top, Controlling the prompt(previous section)
export [-fn] [-p] [name[=value]] …
Mark each name so it is passed to child processes in the environment.
The child process cannot modify the values of names-f name is function; otherwise the names refer to variables.
-n no longer mark each name for export.
-p output in a form that may be reused as input.
If no names are supplied the list of exported names is displayed.
Return status is 0 unless an invalid option is supplied, one of the > export
declare -x EDITOR="vi"
declare -x EXINIT="set showmode ignorecase ruler tabstop=4 mesg verbose exrc"
declare -x HOME="/home2/realge"
declare -x HOSTNAME="slmp-550-13.slc.westdc.net"
declare -x INPUTRC†
declare -x LANG="en_US.UTF-8"
declare -x LC_ALL="en_US.UTF-8"
declare -x LINES="40"
declare -x LOGNAME="realger1"
declare -x MAIL="/var/spool/mail/realg"
declare -x OLDPWD="/home2/realg"
declare -x PAGER="less"
declare -x PATH="/usr/local/bin:/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin:/usr/libexec"
declare -x PS1="\$PWD > "
declare -x PWD="/home2/realger1/www"
declare -x SHELL="/usr/local/cpanel/bin/jailshell"
declare -x SHLVL="1"
declare -x TERM="xterm-256color"
declare -x TZ="US/Eastern"
declare -x USER="realge"
declare -x VISUAL="vi"
names is not a
valid shell variable name, or -f is supplied with a name that is not a shell function.
Notice these examples of environment variables present in a parent (login shell)
which do not have (the same) values in the child as they are not exported.
COLORS
DIRSTACK ~/www
DNS
HISTFILE
HISTFILESIZE
INPUTRC
LIMITUSER
LOCALLIBUSER
MAILCHECK
OSTYPE linux-gnu
PPID 508521
SHELLOPTS braceexpand:hashall:interactive-comments
consoletype
tmpid
whoami
getopts optstring name [args]
parses positional parameters.
Ex: getopts qbvVd: options
A letter followed by a colon the option is expected to have an argument, which should be separated from it by white space.
Each time invoked, getopts places the next option in the shell variable name, initializing name if it does not exist, and the
index of the next argument to be processed into the variable OPTIND is initialized to 1 each time the shell or a shell script is invoked.
When an option has an argument, OPTARG is set to the argument.
OPTIND must be manually reset between multiple calls to
getopts within the same shell invocation if a new set of parameters is to be used.
When the end of options is encountered, getopts exits with a return value greater than 0.
OPTIND is set to the index of the first non-option argument, and
name is set to ?.
getopts normally parses the positional parameters, but if more arguments are given in
args, those are parsed instead.
Errors are reported .
In normal operation diagnostic messages are displayed when invalid options or
missing option arguments are encountered.
OPTERR is set to 0, no error messages will be displayed, even if the first character
of optstring is not a colon.
getopts places ? into name and, if not
silent, prints an error message and unsets OPTARG.
getopts is silent, the option character found is placed in OPTARG and no diagnostic message is displayed.
getopts is not silent, a question mark (?) is placed in name, OPTARG is unset, and a diagnostic message is displayed.
getopts is silent, a : is placed in name and OPTARG is set to the option character found.
OPTERR if 0 supress error display.
name
OPTIND set to index of first non-otion arg OPTARG set to arg of
name set to ? optstring
hash [-r] [-p filename] [command]
Find command in $PATH and remember the full pathname to
avoiding searching on subsequent usages.
See checkhash
-p filename is the location of command, don't search $PATH.
-r reset
The return status is 0 unless a name is not found or an invalid option is supplied. hits command
1 /home2/realger1/.bin/df
1 /home2/realger1/.bin/du
10 /usr/bin/vim
1 /home2/realger1/.bin/stat
1 /home2/realger1/.bin/mysql
command is deleted confusion will result unless shopt checkhash is set.
help
help [pattern]
Display helpful information about builtin commands. If
pattern is specified, help gives detailed help on all
commands matching pattern, otherwise a list of the builtins is
displayed. The return status is zero unless no command matches pattern.
let
let expression [expression]
allows arithmetic to be performed on shell variables.
Each expression is evaluated according to the rules given in Shell Arithmetic.
If the last expression evaluates to 0,
let returns 1 .
export mmdd=`date +%y%m%d
let x=$mmdd-1
> echo $x
1201
(_) how to handle Jaunuary date? ie January 2011 does : 1101 - 1 = 1100 ; not the desired 1012 i.e. december 2010
local
local name[=value]For each argument, a local variable, name, is created,
and assigned value.
local can only be used within a function; scope is restricted to that function and its children.
The return status is 0 unless local is used outside a function or an invalid name is supplied.
logout
logout [n]Exit a login shell, returning a status of
n shell's parent.
printf
printf format [arguments]printf command!arguments standard output under control of format a character
string which contains these types of objects:
In addition to the argument.
printf(1) formats, %b
expands backslash escape sequences in the corresponding argument and
%q
outputs the corresponding argument in a format that can be used as shell input.
The format is reused as necessary to consume all of the arguments.
If the format requires more arguments than are supplied, the extra format specifications behave as if a zero value or null string, as appropriate, had been supplied.
pwd [-LP]
Print the current working directory.
-P the path displayed will not contain symbolic links.
-L the path displayed may contain symbolic links.
The return status is 0 unless an error is encountered while
determining the name of the current directory or an invalid option is supplied.
return [n]
Used by functions to continue execution after the calling statment, with the optional return value n.
May be used to terminate execution of a script being executed with the .† builtin,
returning either n or the exit status of the last command executed within the script as the exit status of the script.
The return status is false if return is used outside a function and not during the execution of a script by .†.
read
read [-a aname] [-p prompt] [-er] [name ...]
One line is read from the standard input, and the first word is assigned
to the first name, the second word to the second name,
and so on, with leftover words and their intervening separators assigned to
the last name. If there are fewer words read from the standard
input than names, the remaining names are assigned empty values. The
characters in the value of the IFS variable are used to split the
line into words. If no names are supplied, the line read is assigned to the
variable REPLY. The return code is zero, unless end-of-file is
encountered.
-r a backslash-newline pair is not ignored, and the backslash is considered to be part of the line.
-p prompt Display prompt, before attempting to read any input, if input is coming from a terminal.
-a aname The words are assigned to sequential indices of the array variable
aname, starting at 0. All elements are removed from
aname before the assignment. Other name arguments are ignored.
-e Readline (Command Line Editing) is used to obtain the line.
readarray|mapfile
reasarrray [-n COUNT] [-O ORIGIN]
[-s COUNT] [-t]
[-u FD]
[-C CALLBACK]
[-c QUANTUM] [ARRAY]
MAPFILE is the default array.
returns success (0) unless an invalid option is given or the given array ARRAY is set readonly.
-c QUANTUM the number of lines that have to be read between every call to the callback. The default 5000
-C CALLBACK shell code, the index of the array that will be assigned, and the line is appended at evaluation time.
-n COUNT at most lines, then terminates. Default 0, all lines
-O ORIGIN Starts populating the array at the index ORIGIN rather than clearing it and starting at index 0.
-s COUNT skips the first lines read.
-t trailing newline are removed
-u FD rather than standard input.
readonly [-apf] [name] ...
Mark each name as readonly. The values of these names may not
be changed by subsequent assignment.
-f each name refers to a shell function.
-a each name refers to an array variable.
If no name arguments are given, or if the
-p option is supplied, a list of all readonly names is displayed.
-p display in a format that may be reused as input.
The return status is 0 unless an invalid option is
supplied, one of the name arguments is not a valid shell variable
or function name, or the -f option is supplied with a name that
is not a shell function.
set
see export
set [--abefhkmnptuvxBCHP] [-o option] [argument ...]
$_ may be very long so this is useful: set | cut -c1-60
Using + (rather than -) causes the option to be turned offsic.
Current options are in $-.
The remaining N arguments are positional parameters and are assigned to > echo $-
himBH$1,
$2, … $N.
The special parameter # is set to N.
The return status is zero unless an invalid option is supplied.
flag -o name
-a allexport Mark variables which are modified or created for export.
-b notify terminated background jobs notify status
immediately, rather than before printing the next primary prompt.
-e errexit Exit immediately if a Simple Command exits with a non-zero status,
unless the command that fails is part of an until or while loop, part of an
if statement, part of a && or
|| list, or if the command's return status is being inverted using !.
-f noglob file name generation (globbing) is disabled.
-h hashall Locate and remember (hash) commands as they are looked up for execution.
default: enabled .
-k keyword Keyword=value format arguments are placed in the environment , not just those that precede the command name.
-m monitor Job control is enabled (Job Control).
-n noexec Read commands but do not execute them
Used to check a script for syntax errors , -v helpful. ignored if interactive .
-o option-nameSet the option corresponding to option-name:
emacs Use an emacs-style line editing interface
(Command Line Editing).
vi Use a vi-style line editing interface.
history Enable command history, See History . Default on if interactive.
ignoreeof An interactive shell will not exit upon reading EOF.
posix POSIX Mode
-p privileged Turn on privileged mode.
$BASH_ENV and $ENV files are skipped.
SHELLOPTS is ignored.
Enabled on startup if effective user/group ID is not real user/group ID.
Turning this option off sets the effective user and group ids to the real user and group ids.
-t onecmdExit after reading and executing one command.
-u nounset Treat unset variables as an error when performing
parameter expansion.
An error message will be written to the standard error, and a non-interactive shell will exit.
-v verbose display input lines as they are read.
> echo $RWS
Real-World-Systems.com
> sh -v myping $RWS
echo ping -c 2 $*
ping -c 2 Real-World-Systems.com
/sbin/ping -c 2 $*
PING real-world-systems.com (205.234.147.106): 56 data bytes
64 bytes from 205.234.147.106: icmp_seq=0 ttl=46 time=39.465 ms
64 bytes from 205.234.147.106: icmp_seq=1 ttl=47 time=39.537 ms
--- real-world-systems.com ping statistics ---
2 packets transmitted, 2 packets received, 0% packet loss
round-trip min/avg/max/stddev = 39.465/39.501/39.537/0.036 ms
-x xtrace execution trace of simple commands and their arguments after they are expanded and before they are executed is displayed.
> echo $RWS
Real-World-Systems.com
> sh -x ping $RWS
+ echo ping -c 2 Real-World-Systems.com
ping -c 2 Real-World-Systems.com
+ /sbin/ping -c 2 Real-World-Systems.com
PING real-world-systems.com (205.234.147.106): 56 data bytes
64 bytes from 205.234.147.106: icmp_seq=0 ttl=47 time=40.511 ms
64 bytes from 205.234.147.106: icmp_seq=1 ttl=46 time=38.524 ms
--- real-world-systems.com ping statistics ---
2 packets transmitted, 2 packets received, 0% packet loss
round-trip min/avg/max/stddev = 38.524/39.517/40.511/0.994 ms
-B braceexpandThe shell will perform Brace expansion
(Brace Expansion). Default on.
-C noclobber Con Cat output;
redirections using >, >&, and <> won't clobber files.
-H histexpand Enable ! style history substitution (History Expansion). Default on for interactive shells.
-P physical If set, The Physical directory is used instead of followng symbolic links when performing commands such as
cd which change the current directory. By default, Bash follows the logical chain of directories when performing commands which change the current directory.
For example, if /usr/sys is a symbolic link to /usr/local/sys then:
default
$ cd /usr/sys; echo $PWD
/usr/sys
$ cd ..; pwd
/usr
If set -P is on, then:
$ cd /usr/sys; echo $PWD
/usr/local/sys
$ cd ..; pwd
/usr/local
-- If no arguments follow this option, then the positional parameters are
unset. Otherwise, the positional parameters are set to the
arguments, even if some of them begin with a -.
- Signal the end of options, cause all remaining arguments to be assigned to the positional parameters. The -x and
-v options are turned off. If there are no arguments, the
positional parameters remain unchanged.
> set -o
allexport off
braceexpand on
emacs off
errexit off
errtrace off
functrace off
hashall on
histexpand on
history on
ignoreeof off
interactive-comments on
keyword off
monitor on
noclobber off
noexec off
noglob off
nolog off
notify off
nounset off
onecmd off
physical off
pipefail off
posix off
privileged off
verbose off
vi on
xtrace off
shopt, bash variables,invoking bash.
shift [n]
Shift the positional parameters to the left by n. The
positional parameters from n+1 ... $# are renamed to
$1 ... $#-n+1. Parameters represented by
the numbers $# to n+1 are unset. n must be
a non-negative number less than or equal to $#.
If n is 0 or greater than $#, the positional parameters are not
changed.
The return status is 0 unless n is greater than
$# or less than 0, non-zero otherwise.
shopt
shopt [-pqsu] [-o] [option ...]
Set variables controlling shell behavior.
cdable_vars off
cdspell off
checkhash off
checkwinsize off
cmdhist on
dotglob off
execfail off
expand_aliases on
extdebug off
extglob off
extquote on
failglob off
force_fignore on
gnu_errfmt off
histappend off
histreedit off
histverify off
hostcomplete on
huponexit off
interactive_comments on
lithist off
login_shell on
mailwarn off
no_empty_cmd_completion off
nocaseglob off
nocasematch off
nullglob off
progcomp on
promptvars on
restricted_shell off
shift_verbose off
sourcepath on
xpg_echo off
-p prints options in a form that may be reused as input.
…
shopt -u extglob
shopt -s extquote
…
set each option. Without option lists the options that are set
-u unset each option. Without option lists the options that are unset
-q Quitely continue, the return status indicates whether the option is set or unset.
If multiple options with -q, the return status is zero if all are enabled; non-zero otherwise.
-o Restricts option to be those for the -o option to the Set builtin.
shopt options are disabled (off) by default.
The return status when listing options is zero if all option are enabled.
When setting or unsetting options, the return status is zero unless an option is not a valid.
The return status when
listing options is zero if all optnames are enabled, non-zero
otherwise. When setting or unsetting options, the return status is zero unless
an optname is not a valid shell option.
cdable_vars if cd doesn't specifiy a directory, it's a variable whose value is a directory.
/home2/realger1 > export docs=/home2/realger1/www/docs
/home2/realger1 > cd docs
/home2/realger1/www/docs >
cdspell cd with minor spelling errors are corrected .
If a corrected , the corrected path is displayed, and the command proceeds. Only for interactive shells.
checkhash check if a command in the hash table
exists before trying to execute it.
If it no longer exists, a normal path search is performed.
checkwinsize updates LINES and COLUMNS after each command incase terminal window was resized.
cmdhist save all lines of a multiple-line command in
the same history entry for easy editing of multi-line commands.
Example:
> for j in 0 1 2
> do
> echo $j
> done
0
1
2
␛k (recall last command if vi is command line editor)
> for j in 0 1 2; do echo $j; done
dotglob include filenames beginning with a `.' in the results of filename expansion.
execfail a non-interactive shell will not exit if it cannot
execute the file specified as an argument to the exec builtin
command.
An interactive shell does not exit if exec fails.
expand_aliases enabled by default for interactive shells.
extglob
extended (pattern matching) is enabled.
histappend the history list is appended to
HISTFILE when the shell exits, rather than overwriting the file.
histreedit with Readline re-edit a failed history substitution is permitted
histverify
with Readline the results of history substitution
are not immediately passed to the shell parser. Instead, the resulting line
is loaded into the Readline editing buffer, allowing further modification.
hostcomplete
with Readline perform
hostname completion when a word containing a @ is being
completed ( Letting Readline Type For You). enabled by default.
huponexit
send SIGHUP to all jobs when an
interactive login shell exits (see Signals).
interactive_comments
Allow a word beginning with # to cause that word and all
remaining characters on that line to be ignored in an interactive shell. enabled by default.
lithist
If enabled, and the cmdhist option is enabled, multi-line
commands are saved to the history with embedded newlines rather than using
semicolon separators where possible.
mailwarn If set, and a file that Bash is checking for mail has been accessed
since the last time it was checked, the message "The mail in
mailfile has been read" is displayed.
nocaseglob
If set, Bash matches filenames in a case-insensitive fashion when performing filename expansion.
nullglob filename patterns which match no files are expanded to a null string, rather than themselves.
promptvars
prompt strings undergo variable and
parameter expansion after being expanded, enabled by default.
shift_verbose
If this is set, the shift builtin prints an error message
when the shift count exceeds the number of positional parameters.
sourcepath
If set, the source builtin uses the value of
PATH to find the directory containing the file supplied as an
argument. This option is enabled by default.
source
source filename
A synonym for . ( dot )
times
Display the user and system times used by the shell and its children.
0m0.060s 0m0.260s
0m1.250s 0m2.240strap [-lp] [
commands] [signal ...]
commands are executed when the shell receives signal signal.
Each signal is a signal name such as INT (SIG prefix is optional ) or a signal number.
Signals ignored upon entry to a shell cannot be trapped or reset.
trap-p displays commands associated with each signal.
trap displays the list of commands associated with each signal number in a form that may be reused as shell input.
trap signal signal is ignored by the shell and commands it invokes.
trap 0 or EXIT commands are executed when the shell exits.
trap DEBUG commands are executed after every simple command.
trap - specified signals are reset to the values they had when the shell was started.
trap-l lists signal names and their corresponding numbers. example from BSD:
signal HUP 1 terminal line HangUP or telnet/ssh dissconnect/exit terminate process
INT 2 INTerrupt program usually ^C see stty -a terminate process
QUIT 3 QUIT program usually ^\ see stty -a core dump
ILL 4 ILLegal instruction core dump
TRAP 5 trace TRAP core dump
ABRT 6 ABoRT program (formerly IOT) core dump
EMT‡ BUS 7 EMulaTe instruction executed core dump
FPE 8 Floating-Point Exception core dump
KILL 9 KILL program terminate process
BUS‡ USR1 10 BUS error core dump
SEGV 11 SEGmentation Violation core dump
SYS‡ USR2 12 non-existent SYStem call invoked core dump
PIPE 13 write on a PIPE with no reader terminate process
ALRM 14 real-time timer expired (alarm) terminate process
TERM 15 software TERMination signal terminate process
URG‡ STKFLT 16 URGent condition present on socket discard signal
STOP‡ CHLD 17 STOP (cannot be caught or ignored) stop process
TSTP‡ CONT 18 Terminal generated SToP signal (i.e. from keyboard) stop process
CONT‡ STOP 19 CONTinue after stop discard signal
CHLD‡ TSP 20 CHiLD status has changed(example: terminated) discard signal
TTIN 21 TTY background INput attempted from control terminal
TTOU 22 TTY background OUtput attempted to control terminal
IO‡ URG 23 I/O is possible on a descriptor (see fCntl ) discard signal
XCPU 24 eXceeded CPU time limit (see setRLimit) ulimit terminate process
XFSZ 25 eXceeded File SiZe limit (see setRLimit) ulimit terminate process
VTALRM26 Virtual Time Alarm (see setITimer) terminate process
PROF 27 PROFiling timer alarm (see setItimer) terminate process
WINCH 28 WINdow size CHange discard signal
INFO &iddagger; IO29 status request from keyboard usually ^t see stty -a discard signal
USR1‡ PWR 30 User defined signal 1 terminate process
USR2‡ SYS 31 User defined signal 2 terminate process
BUS 7 USR1 10 USR2 12 STKFLT 16
CHLD 17 CONT 18 STOP 19 TSTP 20 URG 23 IO 29 PWR 30 SYS 31
RTMIN 34 RTMIN+1 35 … RTMIN+15 49
RTMAX-14 50 RTMAX-13 51 …RTMAX 64
A KILL issued to a process in a wait will cause the wait to expire immediately.
Signals issued by kill -signal PID remain pending if
the script is processing a wait, until the wait expires!
See bash signals.
Trapped signals are reset to their original values in a child process when it is created.
The return status: 1 if sigspec is not a valid signal.
^C
trap "rm -f /tmp/${TMP}*; exit 9" int
write a message to a log if something "bad" happens:
ulimit -Sf 2000 -St 20
trap "echo ' -- trap `date +"%D %T %N"` ?? something bad happened that wasn't my fault, while executing script $0 ??' >> log" TRAP ABRT BUS VTALRM PROF ALRM
trap "echo ' -- trap `date +"%D %T %N"` ?? OOPS. I stumbled ?? '>> log" ILL FPE SEGV STKFLT
trap "echo ' -- trap `date +"%D %T %N"` ?? OOPS. I was stuck in a loop ?? '>> log" XCPU XFSZ
trap "echo ' -- trap `date +"%D %T %N"` ?? sombody poked me with ?? '>> log" INT QUIT USR1 USR2
trap "echo ' -- trap `date +"%D %T %N"` ?? somebody wanted me to stop ?? '>> log" KILL TERM
trap -p
type
[-atp
-t displays alias,
function, builtin, file or
keyword,
If name is not found nothing is displayed, a failure status is returned .
-p returns the name of the file that would be
executed, or nothing if -t would not return file.
-a returns all of the places that contain an executable named
file including aliases and functions, if and only if the
-p option is not used. The return status is zero if any of
the names are found, non-zero if none are found.
typeset
typeset [-afFrxi] [-p] [name[=value]]
The typeset command is supplied for compatibility with the
Korn shell; however, it has been deprecated in favor of declare
ulimit
ulimit [-SHacdflmnpstuv] [limit]
ulimit provides control over resources .
-a display All limits. -S soft limits
-H hard limits
If neither -H nor -S is supplied, both are set.
-t seconds of cpu time
-f size of files created. (1024 byte blocks)
-c size of core files created (seperate from other files).
-n number of open file descriptors.
-d data segment.
-s stack size.
-l size that may be locked into memory.
-m resident set memory size.
-v amount of virtual memory
-u number of user processes
-p pipe buffer size. ( 512 byte blocks)
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
file size (blocks, -f) unlimited
max locked memory (kbytes, -l) unlimited
max memory size (kbytes, -m) unlimited
open files (-n) 256
pipe size (512 bytes, -p) 1
stack size (kbytes, -s) 8192
cpu time (seconds, -t) unlimited
max user processes (-u) 266
virtual memory (kbytes, -v) unlimited
on esc170
ulimit -a -H
core file size (blocks, -c) 0
data seg size (kbytes, -d) 200000
scheduling priority (-e) 0
file size (blocks, -f) unlimited
pending signals (-i) 208896
max locked memory (kbytes, -l) 32
max memory size (kbytes, -m) 200000
open files (-n) 100
pipe size (512 bytes, -p) 8
POSIX message queues (bytes, -q) 819200
real-time priority (-r) 0
stack size (kbytes, -s) 8192
cpu time (seconds, -t) unlimited
max user processes (-u) 20 ←
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited
slmp-550-13.slc.westdc.net
soft & hard limits same
ulimit -a -H
-c 200000 ?
-d 200000
-e 0
-f unlimited
-i 104448
-l 32
-m 200000
-n 100
-p 8
-q 819200
-r 0
-s 8192
-t unlimited
-u 100 ←
-v 512000
-x unlimited
Attempting to change a limit above the hard limit produces the error:
-bash: ulimit: file size: cannot modify limit: Operation not permitted
And returns a status of 1.ulimit affects the current shell environment.
If called in a separate command execution environment, it does not affect the limit of the caller's environment. mkuser , or changed by chuser .
Setting the default limits in /etc/security/limits sets system wide limits, not just limits taken on by a user when that user is created.unlimited is supplied ( status = 2)
as a limit or an error occurs while setting a new limit.
ulimit -t 3
When the total CPU time reaches 3 seconds
Cputime limit exceeded: 24
> tar -cf t *
File size limit exceeded (core dumped)
umask [-p] [-S] [mode]
wikipedia version is good
-Ssymbolic not numeric i.e. rwx not not 027
-p p in format usable as input (Mac OS X darwin
unset [-fv] [name]
Each variable or function name is removed.
With -v or without options name is a variable.
With -f name refers to functions, and the definition is removed.
Readonly variables and functions may not be unset.
The return status is 0 unless a name does not exist or is readonly.
[ expr
Operators and operands must be separate arguments (i.e. surrounded by whitespace).
Parenthsis ( ) groups arguments to override the normal precedence (or improve clarity).
format
0 test
That is only the word test or [ , the expression is FALSE. (and this is useful for ??
1 [ $VAR true if the argument is not null .
2 [ ! $COUNTER
Leading !,
true if the second argument is null. (NOT not null ).
[ -f /loginhush As you would expect:
TRUE if the unary test is TRUE.
If the first argument is a unary conditional operator
If the first argument is not a valid unary operator, the expression is FALSE.
3 [ $SUM -gt 0
If the second argument is one of the binary conditional operators
the result is what you would expect,
[ ( $VAR )
If the first argument is !, the value is the negation of the two-argument test using the second and third arguments.
( xxxx )If the first argument is exactly ( and the third argument is exactly ),
the result is the test of the second argument
Otherwise, the expression is false.
-a and -o are considered binary operators in this case.
4 [ ! $SUM -gt 0
required space after !
leading !, what you would expect
i.e. negative of remaining 3 args as above
Conditional Expressions
used by
The syntax of the
if command.
String
(for example an environment variable)
not necessarily quoted
Numeric
ARG1 and ARG2 are
signed integers
logical
$str1 <† str2
(example where $str1 is an argument)
would $str1 sort before str2 $# -lt n
$# -le n
! negate
$str1 == str2
$str1 = str2
-eq
-a AND
$str1 != str2 not equal.
-ne
-o OR
$str1 >† str2 str1 sorts after str2
-gt
-z $str length of $str is zero.
-n $ str length of $str is not zero.
Results in red may not be as expceted:
> if [ 01 == 1 ]; then echo EQUAL; else echo NO ; fi
NO
(== does a string compare)
EQUAL
EQUAL
(-eq does a numeric compare)
> if [ "1" == 1 ]; then echo EQUAL; else echo NO ; fi
EQUAL
> if [ "1" -eq 1 ]; then echo EQUAL; else echo NO ; fi
EQUAL
TRUE
> if [ 0 ]; then echo TRUE ;fi
TRUE
If any file argument to one of the primaries is of
the form /dev/fd/N, then file descriptor N is checked.
-d its a directory
-a exists
-e exists
if [ -e flagfile ] ; then
echo "flagfile present, I must be already working"; exit
else
echo flagfile was not there.
touch flagfile
echo work, work, work . . .
fi
-s size greater than zero
-N is New (i.e. modified since it was last read)
-r readable -w writable -x executable
-u set-user-id bit is set
-g set-group-id bit is set
-k "sticky" bit is set
-O owned by the effective user id
-G owned by the effective group id
-f regular file.
-L symbolic link
-b block special file
-c character special file
-S socket
-p named pipe (FIFO).
-t fd file descriptor fd is open and
refers to a terminal.
file1 -nt file2
file1 is Newer Than (according to modification date) file2.
file1 -ot file2
file1 is Older Than file2.
file1 -ef file2
file1 and file2 have the same device and inode numbers. (they are hard linked)
-o optname
shell option optname is enabled.
(The list of options appears in the description of -o to the
set builtin.
Shell Arithmetic
let or
as one of the shell expansions.
Division by 0 is trapped and flagged as an error.
Operators are grouped with
+ -
unary plus and minus
! ~ logical and
** exponentiation
* / % multiplication division remainder
+ -addition subtraction
<< >>
<= >= < > comparison
== != equality & inequality
&
bitwise AND
Consider an observed value of x'65' and
a mask of x'0F';
meaning preserve/evaluate the right nibble
x'65'
& x'0F'
x'05'
0110 0101
& 0000 1111
0000 0101
^
bitwise eXclusive OR
Consider an existing value of x'0E'
and a "flip pattern" of x'FC',
i.e. where 1s exist in the pattern, existing bits are flipped,
where
0s exist in the pattern the existing bits are preserved.
x'0E'
^ x'FC'
x'F2'
0000 1110
^ 1111 1100
1111 0010
|
bitwise OR
Consider an existing value of x'05';
and a "enabling" 1st bit, x'80' x'05'
| x'80'
x'85'
0000 0101
| 1000 0000
1000 0101
&&† logical AND
if [ "$myanswer && $youranswer"† ]
||† logical OR
? trueExprResult : falseExpreResult conditional evaluation = *= /= %= += -=
<<= >>= &= ^= |=
assignments
Parameter expansion is performed before the expression is evaluated.
The value of a parameter is coerced to a long integer within an expression.
A variable need not have its integer attribute turned on to be used in an expression. 0x or 0X are hexadecimal (example: 0x0A, 0xFC, 0X0a).
Leading 0 are octal (example: 0777, 0755, 0700).
Otherwise, numbers take the form [base]n, where base
is a decimal number between 2 and 64 representing the arithmetic base, and
n is a number in that base. Default base is 10.
The digits greater than 9 are represented by lowercase letters ,
UPPERCASE LETTERS, _, and @, in that order. If
base is less than to 37, either lowercase and uppercase may be used.
Sub-expressions in parentheses are evaluated first.
Arrays
There is no maximum limit on the size of an array, nor any requirement that members be
indexed or assigned contiguously. Arrays are zero-based. declare explicitly declares an array.
An array is created if a variable is assigned using the
syntax:
The subscript is an arithmetic expression that
evaluates to a number greater than or equal to zero. To explicitly declare an
array, use name[subscript]=value
The subscript is ignored. declare -a name
or declare -a name[subscript]
Attributes may be specified for an array variable using declare and
-r readonly) applies to all members of an array.
name=(value1 ... valuen)
[[subscript]=]string. If the optional
subscript is supplied, that index is assigned to; otherwise the index of the
element assigned is the last index assigned to by the statement plus one.
Indexing starts at zero.
This syntax is also accepted by the declare builtin.
Individual array elements may be assigned to using
the name[subscript syntax. ]=value${name[subscript]}.
Braces avoid conflicts with filename expansion operators.
@ or * as a subscript, expands to all members of the array.
These subscripts differ only when the word appears within quotes (").
If the word is quoted, ${name[*]} expands to a single word with the value of each array
member separated by the first character of the IFS† variable, and
${name[@]} expands each element of name to a separate word.
When there are no array members, ${name[@]} expands to
nothing. This is analogous to the expansion of the special parameters @ and *.
${#name[subscript]} expands to the length of ${name[subscript]}.
If subscript is @ or *, the expansion is
the number of elements in the array.
Referencing an array variable without a subscript references element zero.
unset name[subscript] destroys the array element at index
subscript.
unset name, where name is an array, removes the entire array.
A subscript of * or @ removes the entire array.
declare, local, and readonly
accept -a to specify an array.
read accepts -a to assign a list of words read from the standard input to an array, and can read values from the
standard input into individual array elements.
set and declare display array values in a way that allows them to be reused as input.
pushd adds entries to the stack as it changes the current directory,
popd removes specified entries from the stack and changes the current directory to the directory removed.
dirs displays the contents of the directory stack, or current directory if stack is empty!
$DIRSTACK. dirs [+N | -N] [-clvp]
+N
Displays the Nth directory (counting from the left of the
list (origin zero)
-N
Displays the Nth from the right
-p print the directory stack, one entry per line
-v prefix each entry with its index, one entry per line
-l long format; the default format uses a tilde to denote the home directory.
-c Clears the directory stack
pushd [dir | +N | -N] [-n]
Save the current directory on the top of the directory stack and then
cd to dir, then displays stack.
With no arguments, pushd exchanges the top two directories and changes the current directory to the new top directory.
dir Makes the current working directory be the top of the stack, and then cds to dir.
+N Brings the Nth directory from the left of the list to the top of the list by rotating the stack.
-N Brings the Nth directory from the right to the top of the list by rotating the stack.
-n No cd is performed and no check that dir
is valid!
popd [+N | -N] [-n]
Remove the top entry from the directory stack, and cd to the new top directory.
If the top entry is not valid, the current directory is unchanged and the stack is unchanged. +N Removes the Nth entry, from the left
-N Removes the Nth entry, from the right
-n No cd is performed
Use popd -n to remove an invalid entry.
See cd
Bash executes /home/realger1/www/docs >
/home/realger1/www/docs > pushd ../birding
~/www/birding ~/www/docs
/home/realger1/www/birding > pushd log
~/www/birding/log ~/www/birding ~/www/docs
/home/realger1/www/birding/log > pushd data
~/www/birding/log/data ~/www/birding/log ~/www/birding ~/www/docs
/home/realger1/www/birding/log/data > dirs -v -p
0 ~/www/birding/log/data
1 ~/www/birding/log
2 ~/www/birding
3 ~/www/docs
/home/realger1/www/birding/log/data > popd -2
~/www/birding/log/data ~/www/birding ~/www/docs
/home/realger1/www/birding/log/data > dirs -v -p
0 ~/www/birding/log/data
1 ~/www/birding
2 ~/www/docs
/home/realger1/www/birding/log/data > popd -2
~/www/birding ~/www/docs
/home/realger1/www/birding > dirs -v
0 ~/www/birding
1 ~/www/docs
PROMPT_COMMAND before printing $PS1 or $PS2 (used when for continuation lines)
\a Alert aka bell
\n newline.
\r return. \\ backslash.
\e escape ( x'1B') used to introduce terminal commandsi
Example export PS1='\e[7m>\e[0m '
\d date, in "Weekday Month Date" format (e.g., "Tue May 26").
\t HH:MM:SS \T HH:MM:SS 12-hour format. \@ am/pm
\$ If the effective uid is 0 (i.e.root), #, otherwise $.
\u current username
\w Current Working Directory.
\h
\H hostname, up to the first .
\s name of the shell, the basename of $0 (the portion following the final slash).
\v version of Bash (e.g., 2.00) \V release of Bash, version + patchlevel (e.g., 2.00.0)
\W basename of $PWD.
\! history number of this command.
\# command number of this command.
\nnn character whose ASCII code is octal nnn.
\[ Begin sequence of non-printing characters.
(Used to embed terminal control sequence into the prompt.
\] End sequence