| Go to the table of contents | references to zsh are included because Apple/Mac OS no longer supports bash! | Z Indicates different from zsh Ź Indicates not in zsh
|
| help | echo arrays | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| if | test | do / done | while
| break / exit
| continue
| case / esac
| select
| trap
| eval | exec
| declare
| export
| readonly
| local
| hash
| history
| fc
| let
| alias / unalias
| bind
| printf
| read
| readarray mapfile
| getopts
| shift
| shopt Ź
| source
| times
| time
| type
| builtin
| command
| enable
| ulimit
| umask
| typeset
| logout
| | directory cd
| pwd
| popd / pushd
| dirs
| | job control bg / fg
| jobs
| disown
| kill
| wait
| suspend
| | ||||||||||||||||||
/bin which may have additional options or features.
> ls /bin [ cat mv rm cp ls ed mkdir rmdir link ln unlink chmod sync pwd realpath dd date expr stty wait4path hostname ps test df sleep pax echo kill launchctl bash dash ksh tcsh sh zshCommands marked "No**" under External exist externally implemented as scripts using a builtin command of the same name.
Command External csh sh
! No No Yes
% No Yes No
. No No Yes
: No Yes Yes
@ No Yes Yes
[ Yes No Yes
{ No No Yes
} No No Yes
alias No** Yes Yes
alloc No Yes No
bg No** Yes Yes
bind No No Yes
bindkey No Yes No
break No Yes Yes
breaksw No Yes No
builtin No No Yes
builtins No Yes No
case No Yes Yes
cd No** Yes Yes
chdir No Yes Yes
command No** No Yes
complete No Yes No
continue No Yes Yes
default No Yes No
dirs No Yes No
do No No Yes
done No No Yes
echo Yes Yes Yes
echotc No Yes No
elif No No Yes
else No Yes Yes
end No Yes No
endif No Yes No
endsw No Yes No
esac No No Yes
eval No Yes Yes
exec No Yes Yes
exit No Yes Yes
export No No Yes
false Yes No Yes
fc No** No Yes
fg No** Yes Yes
filetest No Yes No
fi No No Yes
for No No Yes
foreach No Yes No
getopts No** No Yes
glob No Yes No
goto No Yes No
hash No** No Yes
hashstat No Yes No
history No Yes No
hup No Yes No
if No Yes Yes
|
% which kill kill: shell built-in command % ls -l /bin/kill 101584 Nov 1 01:31 /bin/kill* | % which echo echo: shell built-in command dgerman@smac14 docs % ls -l /bin/echo 101184 Nov 1 01:31 /bin/echo* |
arguments and perform redirections.
source) executes commands from cmdfile in the current shell context
as if there were included in the command stream. cmdfile does not contain a slash, $PATH is searched.filename, does not need eXexute permission .cmdfile cannot be read, the return status is 127.
Aliases provide a substitute for first word of a command.
If the last character of value is a [space] or [tab] the next command word is also checked for alias expansion.
Exampe: alias ls="ls -F" causes a subsequent ls to include suffixes.
name may include metacharacters† except =,
value may include metacharacters.
Output aliases on standard output when used without arguments or with -p.
aliases are not expanded in scripts without set expand_aliases=on.
Examples:
alias c='cp --preserve --interactive' alias cd-='cd -' alias cd..='cd ..' alias chdir='cd' alias ci='vi' | alias del='rm' alias edit='vi' alias g='grep' alias h='head -$LINES' alias l.='ls -d . --color=tty' alias ls-l='/bin/ls -l' |
expand_aliases is set.
An alias definition on the same line as another command do not take effect until the next line.
Aliases are expanded when a function definition is read, not when the function is executed. As a consequence,
aliases defined in a function are not available until after that function is executed.
To be safe, put alias definitions on a separate line, and do not use alias in compound commands.
Consider assigning an $environmentVariable to the full-path program and then use that. For Example:
> nrfjprog='/Applications/Nordic Semiconductor/nrfjprog/nrfjprog' > "$nrfjprog" --memrd 0x10000100 # quotes here mitigate the problem of the directory containing and embedded space.If arguments are needed, a shell function should be used.
alias_names. -a all.
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 key and function bindings, or bind a key sequence to a readline function or macro.
.inputrc readline init file.emacs is the command line editor,
Each binding must be passed as a separate argument in emacs format where \C-x is control X and \M-x is ␛x
use "\C-x\C-r":re-read-init-file.
hold the [ctrl] key and press xr
If vi is the command line editor ( set -o vi )
when the line has been recalled using ␛k, bindings as set per vi command mode.
For example to Apppend to the recalled line press an A .
Troublesome key-bindings which cause problems on various keyboards/telnet clients include:
C-? which is sometimes transmitted when the [del] key is pressed.
\C-?: backward-delete-char
Runs
For example: a function named
To have
To cause bash to correct minor spellings in the new current directory use
If
Output
With no options enable the builtin.
enable .
ES=$?
return returns from a function.
See also set
optstring are the option letters to be recognized;
variables used:
If no arguments are given, information about remembered commands is displayed.
If
Display information about builtin commands.
Without
Operators are grouped in levels of equal-precedence , levels are listed in of decreasing precedence.
Shell variables are allowed as operands. The name of the variable
is replaced by its value (coerced to a fixed-width integer) within
an expression. The variable does not need to have integer attribute.
Write
One line is read from the standard input.
Display the list if no options specified:
The return status is
If a command begins with
Sometimes used to cause process to read it's configuration file.
‡Different linux signals:
Example: remove tmp files and exit with a return code of 2 when the terminal user presses
To make a script "safe" by limiting the execution time and filespace it can use and
trap -p # show set traps
If
If BASH receives a signal, for which a trap has been set, while waiting for a command to complete, will not be executed until the command completes.
Commands started by Bash have signal handlers set to the values inherited by the shell from its parent.
Additional signals , passed to process
For each
A Soft limit can be changed up to the maximum set by the Hard limit.
Examples:
ulimit -f 2
See trap XCPU , XFSZ
The return status is
Evaluate a conditional expression.
In this example -exists should be
Example:
used by
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
Don't use to test for null argument see ParamExpansions
The status of a file† can be checked with:
If any
these
>>>>???
Exit Status:
Test if an environmental variable has a value by concatenating it with x; check against null.
See expansion
Arithmetic expressions are be evaluated by Evaluation is done in long integers with no check for overflow.
Variables are allowed as operands. Constants with a leading Operators are evaluated in order of precedence. Array varriables are one-dimensional, zero-based and
are created using
Arrays are assigned using compound assignments of the form
Elements of an array are referenced using
The directory stack is the array Special characters used in the prompt :
After startup, last argument to the previous simple command executed in the foreground, after expansion.
When checking mail, holds the name of the mail file.
To have the home directory searched first use
See
top, Variables (previous section)
An interactive shell is one whose input and
output are both connected to terminals (as determined by
If arguments remain after option processing, and neither
(Tildes are expanded in file names as described in Tilde Expansion.)
When the login shell exits, commands are executed from:
When started non-interactively to run a script interactive login shell, executes commands from:
An interactive shell Bash uses
As defined
Invoking Bash:
An interactive shell is one whose input and output are both connected
to terminals (as reported by
Startup scripts should test the value of break [n]
Exit from a for, while, until, or
select loop.
If n is supplied, the nth
enclosing loop is exited. n must be greater than or equal to 1.
The return status is 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.
The return status is non-zero if shell-builtin is not a shell-builtin command.
command [-pVv] command [arguments …]
command with arguments ignoring any
function named command.
Only builtin commands or commands found by searching the PATH are executed. ls, which includes command ls within the
function, will execute the external command ls instead of calling the function recursively. -p Use default for $PATH that is guaranteed to find all of the standard utilities.
The return status is 127 if command cannot be found, an error occurred or
the exit status of the command .
-v Display the command or file name used to invoke command
-V Produces a more verbose description, the return status is command is found.
> 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 [-LP] [directory]
When files are referenced, the "current directory" is where they are expected to be found.
Specify the path to locate files in another directory, for example ls /home/myname/webProject/index.html.
Change the current directory with cd if frequent access to another directory is needed.
For example: cd /home/myname/webProject
cd without a directory changes to $HOME.
cd - changes to the previous directory. $OLDPWD.
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, shopt -s cdspell
Ź$CDPATH exists, it is used as a search path.
If directory begins with a slash, CDPATH is not used.
i.e. cd /home/myname/dox changes current working directory to /home/myname/dox.
-L follow symbolic links, default (see ln)
-P Prevent symbolic links from being followed.
The return status is
continue [n]
Resume the next iteration of an enclosing for, while, until, or select loop.
If n is supplied, the execution of the nth enclosing loop
is resumed. n must be greater than or equal to 1.
The return status is n is not greater than or equal to 1.
declare [-p | -afFrtxi] [name[=value]]
Declare variables and give them attributes. If no names are given, the values of variables are displayed.
Variable names, attributes and values are displayed.
-F Function names and attributes are displayed.
-f Only functions are displayed.
> declare -f quote
quote ()
{
local quoted=${1//\'/\'\\\'\'};
printf "'%s'" "$quoted"
}
-a array variable (Arrays).
-A Associative array is created. Not
-i integer; arithmetic evaluation (Shell Arithmetic) is performed when the variable is assigned a value.
-r readonly, cannot be set again or unset.
-t Give function the trace attribute
which inherit DEBUG and RETURN traps from the calling shell.
-x export
> declare -p UID
declare -ir UID="501"
integer; readonly > 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"
}
> declare -F
declare -f update_terminal_cwd
Use + instead of - to turn offsic the attribute .
Used in a function, makes each name local, as with local
The return status is
names is not a valid shell variable name
-f foo=bar
-f.
echo [-n[e|E] [args …]
There is a command /bin/echo and there is printf
args separated by spaces, terminated with a newline.
-n no newline output (NOT zsh use /bin/echo)
-e enable the interpretation of the special character codes.
-E no Enabling " … (default!)
Readline will already have processed the backslash so you really need to use \a alert (bell) \b backspace \\ backslash
\f form feed \n new line \r carriage return \t horizontal tab
\v vertical tab
\e escape \c suppress trailing newline
\nnn the character whose ASCII code is the octal value
nnn (1 to 3 digits)
\xnnn the character whose ASCII code is the hexadecimal value
nnn (1 to 3 digits)
\\a … with -e
Hash # begins a comment and stops the echo string,
Environment variables or arg index are prefixed with $ as usual.
enable [-n] [-p] [-f filename] [-ads] [name …]
-n disable builtin shell command.
allowing a file command with that name without specifying a full pathname.
To create a script called test first enable -n test # i.e. disable the builtin test command
This will most likely confuse you later! ed-p print no options or no name arguments : a list all of the builtins(like 61 of them) .
all are enable:
enable|column
. caller disown fc let readonly times unset
: cd echo fg local return trap wait
[ command getopts logout set true
alias compgen eval hash popd shift type
bg complete exec help printf shoptŹ typeset
bind continue exit history pushd source ulimit
break declare export jobs pwd suspend umask
builtin dirs false kill read test unalias
-a list all builtins status.
Example:
% enable -a
" …
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.
The return status is name is not a shell builtin or there is an error loading a new builtin from a shared object.
eval [arguments]
The arguments are concatenated into a single command,
which is read and executed. Its exit status is returned as the exit status of eval.
If there are no arguments or only empty arguments, the return status is
exec [-cl] [-a name] [command [arguments]]
If command is supplied, it replaces the shell without creating a new process.
-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.
If no command is specified, redirections may be used to affect the current shell environment.
If there are no redirection errors, the return status is 0̸; otherwise non-zero.
exit [n]
Exits to the caller of a script with a status of mod(n,256) (default $?
Example:
Any
parent childscript.sh
childScript.sh
if [ $ES -ne 0 ]
fi
… more parent stuff executed if childscript.sh went well.various commands
exit 4
trap on EXIT is executed before the shell terminates.
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.
> 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="reer1"
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/reer1/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"
Return status is names is not a
valid shell variable name or -f is supplied with a name that is not a shell function.
These environment variables in a parent (login shell) do not have the same values in the child .
$COLORS
$DIRSTACK ~/www
$DNS
$HISTFILE /Volumes/DATA/userna/.bash_history
$HISTFILESIZE 1000
$INPUTRC
$LIMITUSER
$LOCALLIBUSER
$MAILCHECK 60
$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
hits command
1 /home2/reer1/.bin/df
1 /home2/reer1/.bin/du
The return status is name is not found or an invalid option is supplied. command is deleted confusion will result unless shopt checkhash is set.
help [pattern]
With pattern dispilays detailed help on all commands matching.pattern builtins are listed.
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin15)
These shell commands are defined internally. Type `help' to see this list.
Use
if a match is displayed the return status is help name to find out more about the function name.
Use info bash to find out more about the shell in general.
Use man -k or info to find out more about commands not in this list.
A star (*) next to a name means that the command is disabled.
JOB_SPEC [&] (( expression ))
. filename [arguments] :
[ arg... ] [[ expression ]]
alias [-p] [name[=value] ... ] bg [job_spec ...]
bind [-lpvsPVS] [-m keymap] [-f fi break [n]
builtin [shell-builtin [arg ...]] caller [EXPR]
case WORD in [PATTERN [| PATTERN]. cd [-L|-P] [dir]
command [-pVv] command [arg ...] compgen [-abcdefgjksuv] [-o option
complete [-abcdefgjksuv] [-pr] [-o continue [n]
declare [-afFirtx] [-p] [name[=val dirs [-clpv] [+N] [-N]
disown [-h] [-ar] [jobspec ...] echo [-neE] [arg ...]
enable [-pnds] [-a] [-f filename] eval [arg ...]
exec [-cl] [-a name] file [redirec exit [n]
export [-nf] [name[=value] ...] or false
fc [-e ename] [-nlr] [first] [last fg [job_spec]
for NAME [in WORDS ... ;] do COMMA for (( exp1; exp2; exp3 )); do COM
function NAME { COMMANDS ; } or NA getopts optstring name [arg]
hash [-lr] [-p pathname] [-dt] [na help [-s] [pattern ...]
history [-c] [-d offset] [n] or hi if COMMANDS; then COMMANDS; [ elif
jobs [-lnprs] [jobspec ...] or job kill [-s sigspec | -n signum | -si
let arg [arg ...] local name[=value] ...
logout popd [+N | -N] [-n]
printf [-v var] format [arguments] pushd [dir | +N | -N] [-n]
pwd [-LP] read [-ers] [-u fd] [-t timeout] [
readonly [-af] [name[=value] ...] return [n]
select NAME [in WORDS ... ;] do CO set [--abefhkmnptuvxBCHP] [-o opti
shift [n] shoptŹ [-pqsu] [-o long-option] opt
source filename [arguments] suspend [-f]
test [expr] time [-p] PIPELINE
times trap [-lp] [arg signal_spec ...]
true type [-afptP] name [name ...]
typeset [-afFirtx] [-p] name[=valu ulimit [-SHacdfilmnpqstuvx] [limit
umask [-p] [-S] [mode] unalias [-a] name [name ...]
unset [-f] [-v] [name ...] until COMMANDS; do COMMANDS; done
variables - Some variable names an wait [n]
while COMMANDS; do COMMANDS; done { COMMANDS ; }
If no command matches:
+++
-bash: help: no help topics match
pattern Try help help or man -k pattern or info pattern.
echo $?
1
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 let returns 1 sic.
Each ARG is an arithmetic expression to be evaluated in fixed-width integers with no check for overflow.
Division by
% let j=3/
zsh: division by zero
bash: let: j=3/
id++ , id-- post-increment , post-decrement
++id , --id pre-increment , pre-decrement
- , + unary minus , plus
! , ~ logical and bitwise negation
exponentiation
, / , % multiplication , division , remainder
+ , - addition , subtraction
<< >> left and right bitwise shifts
<= , >= , < , > comparison
== , != equality , inequality
& , | , ^ bitwise AND, OR, XOR
&& , || logical AND, OR
expr ? expr : expr conditional operator
= , *= , /= , %= ,
+= , -= , <<= , >>= ,
&= , ^= , |= assignment
Operators are evaluated in order of precedence. Sub-expressions in
parentheses are evaluated first and override the precedence rules above.
If the last ARG evaluates to mmdd=`date +%m%d`
> echo $mmdd
1231
> m=$mmdd-1 # no space is permitted after the
(_) how to handle Jaunuary date? ie January 2011 does : 1101 - 1 = 1100 ; not the desired 1012 i.e. december 2010
=
> echo $m
1231-1
> let x=$mmdd-1
> echo $x
1230
> n= 31
-bash: 31: command not found
local name[=value]…
Within a function, for each argument, local variable, name, is created, and assigned value.
The scope is restricted to that function and its children.
return status is name is supplied returns 1 .
funct(){
+ local a=1
+ echo $a
+ }
>funct
1
>echo $a
>
logout[n]
Exit a login shell, returning a status of n shell's parent.
printf format [arguments]
Not to be confused with the printf utility!arguments to standard output under control of format,
a string which contains :
In addition to the \n) converted and copied to standard output
% ) which output the next 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 process all arguments.
If the format specifies more arguments than are supplied,
the extra format specifications behave as if a
pwd [-LP]
Display the current working directory.
-P will not contain symbolic links.
-L may contain symbolic links.
The return status is
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 .† .
exit is for scripts.
read
shell builtin as well as /usr/bin/read builtin `echo ${0##*/} | tr \[:upper:] \[:lower:]` ${1+"$@"} shows lowercase caller ??read [-p prompt] [-er] [-a aname] [name … ]
The characters in IFS † .
(default: IFS=$' \t\n\C-@' i.e tab, newLine and null
(Viewed using set |grep IFS |head -n 1) are used to split the line into words.
The first word is assigned to the first $aname, the second word to the second $aname, …
leftover words and their intervening separators assigned to the last name.
If there are fewer words than names, the remaining names are assigned empty values.
If no names are supplied, the line is assigned to $REPLY with tabs replaced by a single space.
-p prompt Display prompt, before reading input, if input is coming from a terminal.
-e Readline is used to obtain the line. (a good thing)
-a aname words input are assigned to sequential indices of the array variable (NOT
zsh
aname, starting at aname before the assignment. Other aname arguments are ignored.
-r a backslash-newline pair is not ignored, and the backslash is considered to be part of the line.
-k n zsh read "REPLY? Enter a single characer" -k 1
% read -a aarryy
xxxxx yy zzzzz
% set |grep xxxx
aarryy=([0]="xxxxx" [1]="yy" [2]="zzzzz")
% echo $arry[0]
xxxxx[0]
% read -k 1 "REPLY?Press any key to continue: "
Press any key to continue: 1% # I tried to enter 123. read took the 1 and left the 2and 3 for bash.
M% 23
The return code is
1 end-of-file was encountered.
Using + turns the option offsic.
The options can also be specified as arguments to an invocation of the shell.
The current set of options may be found in $-.
The return status is always true unless an invalid option is encountered.
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.
shift [n]
Shift the positional parameters of the fuction to the left by n that is:
reduce the reference of each parameter, starting at the given, number by 1 … and reduce the number of parametrws ($#) by n.
alias eco='/bin/echo -n'
function func() { func aa bb cc
eco #:$#: one:$1:; eco two:$2: #:3: one:aa: two:bb:
shift; eco " <<shifted" <<shifted
eco #:$#: one:$1:; eco two:$2: #:2: one:bb: two:cc:
}
n must ≥ n must ≥ $#.
Parameters previously following the n<>sup>th$0, is not affected.
The return status is
shoptŹ [-pqsu] [-o] [option …]
(1437)
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 an option. Without option lists the options that are set
-u unset an 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 options to be those for the -o option to the set builtin.
shopt options are disabled (off) by default.
Return Status:
option are enabled.
option is not a valid.
cdable_vars if cd doesn't specifiy a directory, it is a variable whose value is a directory. (No $ )
/home2/reer1 > export docs=/home2/reer1/www/docs
/home2/reer1 > cd docs
/home2/reer1/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.
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 on by default for interactive shells,
off by default in scripts
extglob
extended (pattern matching) is enabled.
histappend the history list is appended to
HISTFILE when the shell exits, rather than overwriting the file. See bashHistory
histreedit re-edit a failed substitution is permitted with Readline
histverify Resulting line is loaded into the Readline editing buffer, allowing further modification.
cmdhist Save all lines of a multiple-line command in
the same history entry.
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
lithist
with cmdhist multi-line commands are saved to the history with embedded newlines See bashHistory
hostcomplete hostname completion when a word containing a @ is being
completed with Readline. 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.
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.
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 set shift builtin displays 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. 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.240s
time [-p]
/usr/bin/time is probably what you want!time the elapsed, user and system time consumed by its execution are reported when the pipeline terminates.
The 0.0 wall time; 0.012 user; 0.009 sys; 59.06%
-p option changes the output format to that specified by POSIX.
The real 0.02
user 0.02
sys 0.00
$TIMEFORMAT may be set to a format string.
% introduces an escape sequence that is expanded to a time value or other information.
%% " %"
%[d][l]R
elapsed time in seconds.
%[d][l]U
CPU seconds spent in user mode.
%[d][l]S
CPU seconds spent in system mode.
%P CPU percentage, computed as (%U + %S) / %R. d number of digits after a decimal point, 0-3.
longer format, including minutes, MMmSS.FFs.
Default \nreal\t%3lR\nuser
\t%3lU\nsys\t%3lS
In posix mode, time may be followed by a newline. displays the total user and system time consumed by the shell and its children.
In posix mode, time is not recognized if the next token begins with a -.
Signals ignored upon entry to a shell cannot be trapped or reset.
trap-p displays commands associated with each signal.
trap displays 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.
signals reset to the values when the shell was started.
trap-l lists signal names and their corresponding numbers.
signal description Default action
EXIT0 shell exited
DEBUG occurs after EVERY simple command. (noisy) example: trap 'date +%T' DEBUG
See declare -t name
ERR a simple command returns non-zero. example: trap 'echo " -- RC:$?"' ERR
RETURN function or script executed with the .† or source builtins finishes.
See declare -t name
HUP 1
telnet|ssh dissconnect/exit.
Another process issued kill -hup pid.
Terminal line hungup (Disconnected).
If bash huponexit is set, bash sends HUP to all jobs when an interactive login shell exits.
terminate process INT 2 Interrupt. Usually ^C from controlling terminal. See stty -a
terminate process
TERM 15 Termination signal
Issued by shutdown a few moments before issuing kill
This is to permit processes to exit cleanly. terminate process
QUIT 3 Quit. Usually ^\ from the controlling terminal See stty -a.
Another process issued kill -quit pid
bash reports line n: pid Quit .
from another terminal:
kill -quit 5288
produces:Quit: 3
Typing ^c at the terminal that issued trap ..echo "I Quit!"
^\Quit: 3 (from the shell zsh)
^C quit (from the script TRAP command).
Terminates sleep and continues script.I Quit!
KILL 9 terminate process CANNOT BE TRAPPED!
outputs Killed: 9 with $? = 137
STOP‡ CHLD 17 Cannot be caught or ignored) Stop process
CONT‡ STOP 19 Continue after stopDiscard signal
ABRT 6 Abort (formerly IOT) core dump
ILL 4 ILLegal instruction core dump
TRAP 5 trace TRAP core dump
EMT‡ Bus 7 EMulaTe instruction executed core dump
FPE 8 Floating-Point Exception core dump
BUS10 Bus error core dump
SEGV 11 Segmentation Violation core dump
SYS‡ USR2 12 non-existent system call invoked core dump
kill -usr2 5288
User defined signal 2: 31
from another terminal session: kill -sys 5231
/Users/xan/.bin/taill: line 28: 5231 Bad system call: 12 tail -n$x $1 $lastFile
PIPE 13 write on a PIPE with no reader terminate process
ALRM 14 real-time timer expired (alarm) terminate process
URG‡ STKFLT 16 Urgent condition present on socket discard signal
TSTP‡ CONT 18 Terminal generated stop process
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
IOSee 29
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 ‡ 29 status request from keyboard usually ^t see stty -a Discard signal.
Some programs ( for example dd) report progress.
reports: I/O possible
USR1‡ PWR 30 User defined signal 1 terminate process
USR2‡ SYS 31 User defined signal 2 terminate process
POSIX.1-2024
sigwait() for thread-safe signal handling,
when SA_SIGINFO is set requires explicit casting to ucontext_t *
SIGWINCH Window changes size.
raise() is async-signal-safe even from within a signal handler.
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!
Trapped signals are reset to their original values in a child process when it is created.
Return status: 1 if sigspec is not a valid signal.
^c
trap "rm -f /tmp/${TMP}*; exit 2" SIGint
write a message to a log if something "bad" happens:
ulimit -Sf 2000 -St 20 # set soft limits for files (KB) and cputime(seconds)
export LOG=" ~/log/trap.log"
echo LOG:$LOG
date +"%D %T"
trap "echo ' -- trap `date +"%D %T"` OOPS. I was stuck in a loop ' >> $LOG \
CLeanThingsUp.sh ; exit 24" XCPU XFSZ
trap "echo ' -- trap `date +"%D %T"` OOPS. I stumbled ' >> $LOG; tail $LOG; exit 4" ILL FPE SEGV URG
trap "echo ' -- trap `date +"%D %T"` Sombody poked me ' >> $LOG; tail $LOG;exit 2" INT QUIT USR1 USR2
trap "echo ' -- trap `date +"%D %T"` Something happened that was not my fault, executing $0 ' >> $LOG; exit 5" TRAP ABRT BUS VTALRM PROF ALRM
trap "echo ' -- trap `date +"%D %T"` Somebody wanted me to terminate ' >> $LOG; exit 15" TERM
# Kill cannot be caught
trap -- 'echo good bye ' EXIT
> logout
good bye
Connection to real-world-systems.com closed.
Signals Handled by bash
See trap for prempting signals for a script.
default
keystrokes see stty
> stty -a
…
cchars: discard=^O; dsusp=^Y; eof=^D; eol=
intr=^C; quit=^\; killcharacters typedAhead=^U; eof=^D; eol=<undef> eol2=SIG QUIT^\ ignored.
SIG TERM^c ignored when Bash is interactive, in the absence of any traps,
kill TERM p does not terminate an interactive shell
SIG INT^c caught and handled (so that wait is interruptible) and
bash breaks out of any loops.
Ignored by asynchronous commands
SIG TTIN
SIGTTOU
SIGTSTP ignored if Job Control is in effect.
ignored for commands run as a result of command substitution
SIG HUP Causes the shell to exit by default. Before
exiting, all job are sent SIG HUP .
Stopped jobs are first sent SIGCONT to ensure that they receive the
SIGHUP.
To prevent the shell from sending the SIGHUP
signal to a particular job, it should be removed from the jobs table with
disown (see Job
Control) or marked to not receive SIGHUP using disown -h.
huponexit is set
bash sends SIGHUP to all jobs when an interactive login shell exits.
If waiting for an asynchronus command a status greater than 128 is set, then trap is executed.
type
[--afPt†pa]
[name …]name, display how it would be interpreted as a command.
Output is shown on the same line for clarity. ed
-a all of the places that contain an executable named keyword,
-p file that would be executed, or nothing if -t would not return file.
file including aliases and functions, if and only if the
-t display the type i.e. alias, function, builtin, file or keyword.
-p option is not used.
The return status is names are found, non-zero if none are found.
> type wc wc is /usr/bin/wc
> type SHELLOPTS -bash: type: SHELLOPTS: not found
> type sopt -bash: type: sopt: not found
> type shopt shopt is a shell builtin
> type set set is a shell builtin
> type { { is a shell keyword
> type emacs emacs is /usr/bin/emacs
> type errexit -bash: type: errexit: not found
> type cd cd is a shell builtin
> type CD CD is /usr/bin/CD surprise ?
> type ls ls is aliased to `ls -F'
> type -t ls alias
> type -a ls ls is aliased to `ls -F'
ls is /bin/ls
> type echo echo is a shell builtin
> type ECHO ECHO is /bin/ECHO uppercase! surprise ?
> type -a ECHO ECHO is /Volumes/DATA/dgerman/.bin/ECHO
ECHO is /bin/ECHO
> type -a echo echo is a shell builtin
echo is /Volumes/DATA/dgerman/.bin/echo
echo is /bin/echo
ulimit [-S|H] [-a]|[-cdflmnpstuv] [value]
Provides control over resources, useful in preventing "run-away" processes.
When setting limits both are set by detault (not the best idea).
-S Soft limits
-H Hard limits
-a display all limits. -t seconds of cpu time (not wall tme)
-f files size used. (1024 byte blocks)
-u number of user processes
-p pipe buffer size. ( 512 byte blocks)
-n number of open file descriptors. -c core (dumps) file space used(seperate from other files).
-d data segment size.
-s stack size.
-l size that may be locked into memory.
-m resident set memory size.
-v amount of virtual memory
Once a process decreases a Hard limit it cannot be increased.
ulimit affects the current shell environment, it does not affect the limits of the caller .
ulimit -t 3
When the total CPU time reaches 3 seconds
Cputime limit exceeded: 24
> tar -cf t *
File size limit exceeded (core dumped)unlimited) is supplied ( status = 2)
as a limit or an error occurs while setting a new limit.
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.
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
test expr
also written as [expr
Operators and operands must be separate arguments (i.e. surrounded by whitespace).
Parenthesis ( ) groups arguments to override the normal precedence (or improve clarity).
#† format result exception
1 test $var
TRUE if $var is TRUE TRUE if $var is not null i.e. $VAR has been assigned a value (perhaps within a function).
test ! $var
TRUE if $var is FALSE. (negation).
TRUE if $var is null.
test -f loginhush TRUE
if the evaluation is TRUE.
In this example -f "is a regular file".
FALSE if the operator
is not a
-e
3 test $SUM -gt 0
test ( $VAR )
If the 1st argument is !, the value is the negation of the
2 argument test 2nd and 3rd arguments.
( xxxx ) the result is the test of xxxx
Otherwise, the expression is false.
-a (and) and -o (or) are considered logical binary operators in this case.
4 test ! $SUM -gt 0
required space after ! leading !, i.e. negative of remaining 3 args as above
If the touch is successful the return code ( ${?} ) will be equal to 0 and
the exit statment ( part of the OR list ) will NOT be executed. The script will continue.touch CMakeLists.txt
test ${?} -eq 0 || ( echo "-- failed, exiting"; exit $rc
Similarily if the return code is NOT 0, the AND list WILL be executed. test ${?} -ne 0 && exit ${?}
See command lists for even simpler example involving the return code>
Conditional Expressions
See simple list of commands like:
try_to_do_stuff && do_more_stuff_since_it_is_going_well
try_to_do_stuff || clean_up_mess_from_failured_stuff
The syntax of the
if command.
-bash: [: -eq: unary operator expected Is reported when attempting to compare an unset $variable.
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
zsh doesn't support == within the [ ] test command,
Use [[ ]].
-eq -a AND
$str1 != str2 not equal.
-ne
$rc -ne 0 exit $rc -o OR
$str1 >† str2 if [ $rc >1 ]; then echo "oops";fi
AND file 1 is klobbered!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
(-eq does a numeric compare)
EQUAL
> 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
-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
-d its a directory -s size greater than zero
-N is New, i.e. modified since it was last read.
-r readable -w writable if [ ! -x f ]; then NOT executable
(perhaps `which name` is better since it searches $PATH
-u set-user-id is set
-g set-group-id 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
-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)
file argument to one of the primaries is of
the form /dev/fd/N, then file descriptor N is checked. -z $str length of $str is
-n $str length of $str is not -o optname shell option optname is enabled.
(The list of options appears in the description of -o to the set builtin.
-h file True if file is a symbolic link.
-O file True if the file is effectively owned by you.
-G file True if the file is effectively owned by your group.
if FILE is a symbolic link, file operators except -h and -L refer to the target of a symbolic link, not on the symlink itself,
String operators:
-o option True if the shell option is enabled.
-v $VAR True if the shell variable $VAR is set.
-R $VAR True if the shell variable $VAR is set and is a name reference.
arg1 OP arg2 Arithmetic tests. OP is one of -eq, -ne, -lt, -le, -gt, or -ge.
Arithmetic binary operators return true if arg1 is
equal, not-equal,
less-than, less-than-or-equal, to
arg2.
Returns success if EXPR evaluates to true; fails if EXPR evaluates to false or an invalid argument is given.
if [ "$VAR"x = ""x ] ; then … "${1:-}" to test function argument.
Shell Arithmetic
let
> let i=$j+4 ; echo $i #
or as a shell expansion.
no spaces!
12 > echo $((13/6))
2
Division by 0 is trapped and flagged as an error. $ r=0
% let c=1/$r
-bash: let: c=1/0: division by 0 (error token is "0")
Operators in order of decreasing precedence,
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
> let x=8; let x+=9; echo $x
17
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
declare -a name
The index is an arithmetic expression that evaluates to
Attributes may be specified for an array variable using declare and
-r (readonly) applies to all members of an array. name=(value1 … valueN)
where each value is of the form
[[index]=]string.
If the index is supplied, that index is assigned to; otherwise the index is the last index assigned plus one.
This syntax is also accepted by declare.
Individual array elements may be assigned to using the name[subscript=value. declare -a to display all arrays and attributes.${name[subscript]}.
An index of @ or * expands to all members of the array.
These indexes 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[index]} expands to the length of ${name[index]}.
If index is @ or *, the expansion is the number of elements in the array.
Referencing an array variable without a subscript references element zero.
unset name[index] destroys that array element .
unset name removes the entire array as does a subscript of * or @.
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. $DIRSTACK.
set|grep DIRS
echo $DIRS
DIRSTACK=([0]="~" [1]="/Volumes/homes/sams/Documents/computerstuff/firmware" [2]="/Volumes/DATA/homes/sams/bin")
dirs displays the directory stackZ, or current directory if stack is empty!
+N
Displays the Nth directory (counting from the left of the list (origin zero)
-N Displays the Nth from the right
dirs [+N | -N] [-clvp]
Not zsh:
-p display the directory stack, one entry per line
-v prefix each entry with its index, one entry per line dirs -v
0 ~
1 ~/mail/real-systems.com/dgerman
2 ~/mail/real-systems.com
3 ~/mail
4 ~
5 ~/www/docs
-l long format; the default format uses a tilde to denote the home directory. /home/sam /home/sam/mail/real.com/dgerman /home/sam/mail/real.com /home/sam/mail /home/sam /home/sam/www/docs
-c Clears the directory stack
pushd [dir | +N | -N] [-n]
adds entries to $DIRSTACK as it changes the current directory,
Save the current directory on the top of the directory stack and then
cd to dir, then displays $DIRSTACK.
With no arguments, pushd changes back to the previous directory by
exchanging 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]
removes entries from the stack and changes the current directory to the directory removed.
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.
/home/rear1/www/docs > pushd ../birding
~/www/birding ~/www/docs
/home/reer1/www/birding > pushd log
~/www/birding/log ~/www/birding ~/www/docs
/home/reer1/www/birding/log > pushd data
~/www/birding/log/data ~/www/birding/log ~/www/birding ~/www/docs
/home/reer1/www/birding/log/data > dirs -v -p
0 ~/www/birding/log/data
1 ~/www/birding/log
2 ~/www/birding
3 ~/www/docs
/home/reer1/www/birding/log/data > popd -2
~/www/birding/log/data ~/www/birding ~/www/docs
/home/reer1/www/birding/log/data > dirs -v -p
0 ~/www/birding/log/data
1 ~/www/birding
2 ~/www/docs
/home/reer1/www/birding/log/data > popd -2
~/www/birding ~/www/docs
/home/reer1/www/birding > dirs -v
0 ~/www/birding
1 ~/www/docs
See cd
Bash executes PROMPT_COMMAND before displaying $PS1 or $PS2 (used when for continuation lines)
$ENVIRONMENT VARIABLES
$PROMPT_DIRTRIM number of trailing directory components for \w and \W
$PROMPT_COMMANDexecuted prior to issuing primary prompt.
Example including setting the prompt with color coding: \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 ' This sets characters dim, displays > and resets caracter attributes.
\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 #, 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 like terminal control sequences for example colors
\] End sequence
PS1='\[\e[32m\]\u@\h\[\e[0m\]:\[\e[34m\]\w \$\[\e[0m\]'
Where 32m sets green; \u displays the username, , \h the host, and 0m resets the color to black.
Myuname@THeHostIamOn:/home/myhome
See ANSI Characteres
~(underscore)
$_At shell startup, the pathname used to invoke the shell or shell script
being executed as passed in the environment or argument list.
Full pathname used to invoke each command executed and placed in the environment exported to that command. HOME current user's home directory; default for cd and used by Tilde Expansion.
IFS Input Field Seperaters, list of characters that separate fields; used when spliting words as part of expansion.
MAIL If set to a filename and $MAILPATH is not set, Bash informs the user of the
arrival of mail in the file.
MAILPATH Colon separated list of entries periodically checked for new mail, in the form: filename[?message]
In message, $_ expands to the filename.
MAILCHECK Seconds to check for mail in the files specified in $MAILPATH or $MAIL.
OPTARG Value of the last option argument processed by getopts
OPTIND Index " " " " "
CDPATH Colon-separated list of directories used as a search path for cd.
PATH Colon separated list of directories searched (left to right) to locate a command.
Example: echo $PATH
/usr/bin:/bin:/sbin:/usr/local/bin
If home directory is not in $PATH use ~/scriptname or
if the current directory are in $HOME use ./scriptname.export PATH=~:$PATH
$PS1 Primary prompt string, default \s-\v\$
(i.e. shellname-version$).
Often set in .profile to export PS1='$PWD > ' resulting in the display of the Working Directory as the prompt.
PS2 Secondary prompt string used for continuation lines default > ,
perhaps export PS2=' + ' is a better choice.
$PS3 select prompt . Default #?
$PS4 Prompt before command is echoed with -x xtrace set.
The first character of PS4 is replicated multiple times, as necessary, to indicate multiple levels of indirection.
The default is + .
$PROMPT_COMMAND a command executed before the outputting primary prompt ( $PS1).
BASH full pathname used to execute the current instance of Bash.
BASH_ENV Name of a startup file to read before executing the script.(subject to expansion)
BASHOPTS A colon-separated list of enabled shell options.
Each word is a valid argument for shopt -s opt.
When Bash starts, each shell option in the list will be enabled before reading any startup files.
ReadOnly. echo $BASHOPTS
cmdhist:expand_aliases:extquote:force_fignore:hostcomplete:interactive_comments:login_shell:progcomp:promptvars:sourcepath
BASHID
Process ID of the current Bash process. This differs from BASH_ALIASES List of aliases
BASH_ARGC
BASH_ARGE
BASH_ARGV
BASH_ARG0
BASH_COMMAND
BASH_COMPAT
BASH_ENV
BASH_EXECUTION_STRING
BASH_LINENO
BASH_LOADABLES_PATH
BASH_REMATCH
BASH_SOURCE
BASH_SUBSHELL
BASH_XTRACEFD
COLUMNS
EPOCHREALTIME
EPOCHSECONDS
DIRSTACK contents of the directory stack in an Array
in the order they are displayed by dirs .
pushd and popd add and remove directories.
Assignment to this variable does not change the current directory.
If DIRSTACK is unset, it loses its special properties.
FCEDIT editor used by default by -e to edit history fc .
FIGNORE filename suffixs to ignore when performing filename completion, colon-separated list
A sample value is .o:~ to ignore object file and edit backups.
GLOBIGNORE A colon-separated list of patterns defining the set of
filenames to be ignored by filename expansion. If a filename matched by a
filename expansion pattern also matches one of the patterns in
GLOBIGNORE, it is removed from the list of matches.
GROUPS An array variable containing the list of groups of
which the current user is a member. readonly.
histchars†
Using
history !^# are normally used .
Up to three characters which control History Expansion , quick substitution, and tokenization
See shopt options
!.
^.
#.
It does not necessarily cause the shell to treat the rest of the line as a comment.
HISTCMD Set to the index in the history list of
the current command. If HISTCMD is unset, it loses its special properties, even if it is subsequently reset.
HISTCONTROLignorespace don't enter lines which begin with a space or tab into the history list.
ignoredups don't enter lines which match the last entered line (even cd .. (maybe not a good idea ed).
ignoreboth combines the two options.
Unset, or set to any other value than those above, means to save all lines on the history list.
The second and subsequent lines of a multi-line compound command are always added to history.
HISTIGNORE A colon-separated list of patterns used to determine which
command lines are saved on the history list.
Each pattern is anchored at the beginning of the line and must fully specify the line (no implicit * is appended).
Each pattern is tested against the line after the checks specified by HISTCONTROL are applied.
& matches the previous history line. To include & in the pattern escape using a backslash
Continuation lines of a multi-line compound command are not tested, and are always added .
HISTIGNORE subsumes the function of HISTCONTROL.
A pattern of & is identical to ignoredups, and
a pattern of [ ]* is identical to ignorespace.
Combining these two patterns, separating them with a colon, provides the
functionality of ignoreboth.
HISTFILE file to which the command history is saved. default ~/.bash_history.
HISTSIZE maximum number of commands to remember on the history list.
HISTFILESIZE maximum number of lines contained in the history file.
HOSTFILE file in the same format as
/etc/hosts that should be read when the shell needs to complete a
hostname. You can change the file interactively; the next time you attempt to
complete a hostname, Bash will add the contents of the new file to the already existing database.
HOSTNAME The name of the current host.
HOSTTYPE A string describing the machine Bash is running on.
IGNOREEOF Controls the action of the shell on receipt of an
EOF character as the sole input. If set, the value denotes the
number of consecutive EOF characters that can be read as the
first character on an input line before the shell will exit. If the variable
exists but does not have a numeric value (or has no value) then the default is
10. If the variable does not exist, then EOF signifies the end of
input to the shell. This is only in effect for interactive shells.
INPUTRC Readline startup file . Default: ~/.inputrc.
LINENO The line number in the script or shell function currently executing.
MACHTYPE the system type in the standard GNU cpu-company-system format.
(ex: i686-redhat-linux-gnu)
OSTYPE A string describing the operating system. (example linux-gnueabihf)
OPTERR If 1, displays error messages generated by getopts
PIPESTATUS list of exit status values from the processes in the
most-recently-executed foreground pipeline (example ([0]="0"), as an Array
PPID parent process ID . readonly.
PWD Current working Directory set by cd .
OLDPWD previous Working Directory set by cd, used by cd -
RANDOM Each time this parameter is referenced, a random
integer between
Assigning a value to this variable seeds the random number generator.
REPLY The default variable for the read builtin.
SECONDS
since SECONDS was last assigned. ( Initialy assigned when bash starts).
Useful for timing a section of a script.
> cat timeit > sh -x timeit
SECONDS=start # assign to anything resets + SECONDS=start
time find . -name ss + find . -name ss
. -name ss
./vacation/2019/iceland/ss
++++++++++++++++++++++++++++++++++++++++
1 /tmp/find
16.6 wall 0.039 user 0.171 sys 1.26%
output from
echo $SECONDS + echo 17
17
without sh -x: > ./timeit
. -name ss
./vacation/2019/iceland/ss
++++++++++++++++++++++++++++++++++++++++
1 /tmp/find
16.8 wall 0.039 user 0.171 sys 1.26%
17
time commandSHELLOPTS A colon-separated list of enabled shell options.
Each word in the list is a valid argument for the -o option to set.
The options appearing in SHELLOPTS are those reported as on by set -o.
If in the environment when Bash starts up, each shell option in the list will be enabled before reading any startup files. readonly.
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
echo $SHELLOPTS
braceexpand:hashall:histexpand:interactive-comments:monitor:vi
SHLVL
Incremented by one each time a new instance of Bash is started. Level of how deeply shells are nested.
TIMEFORMAT
format string specifying how the timing information for pipelines prefixed with
time should be displayed.
% introduces an escape sequence that is expanded to a time value or other information.
%% " %"
%[d][l]R
elapsed time in seconds.
%[d][l]U
CPU seconds spent in user mode.
%[d][l]S
CPU seconds spent in system mode.
%P CPU percentage, computed as (%U + %S) / %R. d number of digits after a decimal point, 0-3.
longer format, including minutes, MMmSS.FFs.
Default \nreal\t%3lR\nuser
\t%3lU\nsys\t%3lS
real 0m1.000s
user 0m0.000s
sys 0m0.000s
export TIMEFORMAT="%1R wall %U user %S sys %P%%"
0.1 wall 0.103 user 0.020 sys 78.64%
A newline is added.
TMOUT seconds bash waits for input after issuing the primary prompt before exiting.
UID numeric real user id of the current user .readonly.
EUID numeric effective user id of the current user. readonly.
LANG locale category for any category not specifically selected with a variable starting with LC_.
LC_ALL overrides the value of LANG
and any other LC_ specifys locale category. (default: null).
LC_COLLATE
collation order used when sorting the results of filename expansion, and behavior of
range expressions, equivalence classes, and collating sequences within
filename expansion and pattern matching (
Filename Expansion).
LC_CTYPE
interpretation of characters and the behavior of character classes within filename expansion and
pattern matching (Filename
Expansion).
LC_MESSAGES
locale used to translate double-quoted strings preceded by a $
(Locale-Specific Translation).
BASH
The full pathname used to execute the current instance of Bash, example: /bin/bash
BASH_VERSION
The version number of the current instance of Bash.
ex: BASH_VERSION='2.05b.0(1)-release'
BASH_VERSINFO
A readonly array variable whose members hold version
information for this instance of Bash.
example:
BASH_VERSINFO[0] The major version number (the release).
BASH_VERSINFO[1] The minor version number (the version).
BASH_VERSINFO[2] The patch level.
BASH_VERSINFO[3] The build version.
BASH_VERSINFO[4] The release status (e.g., beta1).
BASH_VERSINFO[5] The value of MACHTYPE.
BASH_VERSINFO=([0]="2" [1]="05b" [2]="0" [3]="1" [4]="release" [5]="powerpc-apple-darwin8.0")
Invoking Bash
Usually bash is invoked at login as specified in /etc/passwd or
as the first line of a script using #!/bin/bash
bash [long-options][-ir][-abefhklmnptuvxdBCDHP][-o option][argument …
bash [long-options] [-abefhkmnptuvxdBCDHP] [-o option] -c string [argument …]
bash [long-options] -s [-abefhkmnptuvxdBCDHP] [-o option] [argument …]
set options
Multi-character options must appear before the single-character options
--init-file filename == filename
Execute commands from filename (instead of ~/.bashrc) in an interactive shell.
Startup Files description of the special behavior of a login shell.
--noprofile Don't load ANY startup files ( system-wide /etc/profile,
~/.bash_profile, ~/.bash_login, or ~/.profile) when invoked as a login shell.
--norc Don't read the ~/.bashrc in an interactive shell. on by default invoked as sh.
--rcfile filename Execute commands from filename (instead of ~/.bashrc) in an interactive shell.
--noediting Do not use readline
--restricted
-rMake the shell a restricted shell (The Restricted Shell).
--login
-lact as if directly invoked by login. equivalent to exec -l bash but can be issued from another shell, such as csh. exec bash --login will replace the current shell with a Bash login shell.
--posix Bash POSIX Mode
--dump-strings
-DA list of all
strings that are subject to language translation when the current locale is not C
is displayed on the standard ouput as double-quoted strings preceded by $.
output is in the GNU gettext PO (portable object) format.
POSIX (Locale-Specific
Translation). Implies -n ; no commands will be executed.
--verbose shows startup scripts too
--help
reformatted
GNU bash, version 3.2.57(1)-release-(x86_64-apple-darwin15)
Usage: /bin/bash [GNU long option] [option] ...
/bin/bash [GNU long option] [option] script-file ...
GNU long options: --debug --debugger --dump-po-strings --dump-strings --help --init-file --login
--noediting --noprofile --norc
--posix --protected --rcfile --restricted --verbose --version --wordexp
Shell options: -irsD or -c command or -O shopt_option (invocation only)
-abefhkmnptuvxBCHP or -o option
Type `/bin/bash -c "help set"' for more information about shell options.
Type `/bin/bash -c help' for more information about shell builtin commands.
Use the `bashbug' command to report bugs.
--version GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin15)
Copyright (C) 2007 Free Software Foundation, Inc.
[±]O [shopt_option]
shopt_option one of the shell options accepted by the shopt builtin
If shopt_option is present, -O sets the value ; +O unsets it.
If shopt_option is not supplied, the names and values of the shell options accepted by shopt
are displayed on the standard output.
If the invocation option is +O, the output is displayed in a format that may be reused as input.
Single-character options that may be supplied at invocation
which are not available with the set builtin.
‑c string execute commands from string
after processing the options, then exit.
Remaining arguments are assigned to the positional parameters, starting with $0.
-i Force the shell to run interactively.
-s Commands are read from STDIN if this option is present, or
if no arguments remain after option processing.
This option allows the positional parameters to be set when invoking an interactive shell.
-- signals the end of options and disables further option
processing. Any arguments after the -- are filenames and arguments.
--debugger
isatty(3)), or one started with -i . -c nor -s has been specified,
the first argument is a file containing shell commands (Shell Scripts).
Invoked in this fashion, $0 is set to
the name of the file, and the positional parameters are set to the remaining arguments.
Bash reads and executes commands from this file, then exits.
Exit status is the exit status of the last command executed in the script.
If no commands are executed, the exit status is
Files which exist but cannot be read, are reported as an error.
/etc/profile
~/.bash_profile (Frequently includes a statment to run .bashrc).
~/.bash_login
~/.profile
--noprofile inhibits this.
~/.bash_logout
rshd,
commands are executed from:
~/.bashrc (if it exists and is readablea).
--norc inhibits this.
--rcfile file use file instead of ~/.bashrc.
after (or before) any login-specific initializations.(?) Ed. rshd does not generally invoke the shell with those options or allow them to be specified.
$BASH_ENV is used as the file to execute.
As if if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi were executed.
$PATH is not used to search for the file.
sh, bash mimics the startup behavior of historical versions of sh and conforms to the POSIX standard.
/etc/profile
~/.profile
--noprofile inhibits this .$ENV to execute.
A non-interactive shell does not read any startup files. --posix, it follows the POSIX standard for startup files.
In this mode, interactive shells use the $ENV and executes from that file.
No other startup files are read.
If Bash is started with the effective user (group) id not equal to the real user (group) id:
If $SHELLOPTS is ignored and -p is supplied the effective user id is not reset.
Is This Shell Interactive?
isatty(3)), or
one started with the -i option.
This is reflecgted in the $- special variable with the presents of an i.
$- special parameter.
With a line like:
echo $- |grep --quite i || return # if not interactive return
before any output is generated otherwise sftp
will report:Received message too long #### and refuse to connect!
top