Go to the table of contents.
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
| |
arguments
and perform redirections.
source
) executes commands from filename
in the current shell context
as if there were included in the command stream. 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
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.
Print aliases on the standard output when used without arguments or with -p
.
aliases are not expanded in scripts without set expand_aliases=on
.
alias c='cp --preserve --interactive' alias cd-='cd -' alias cd..='cd ..' alias cdb='cd www/birding/log' 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='ls -og' alias ls-='ls' 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_name
s. -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
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
-m keymap | Use keymap to be in effect on subsequent bindings. emacs , emacs-standard , emacs-meta , emacs-ctlx , vi , vi-command or vi-insert . | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-l | List the names of all Readline functions.
i.e. abort accept‑line alias‑expand‑line arrow‑key‑prefix backward‑byte backward‑char backward‑delete‑char backward‑kill‑line backward‑kill‑word backward‑word beginning‑of‑history beginning‑of‑line call‑last‑kbd‑macro capitalize‑word character‑search character‑search‑backward clear‑screen complete complete‑command complete‑filename complete‑hostname complete‑into‑braces complete‑username complete‑variable copy‑backward‑word copy‑forward‑word copy‑region‑as‑kill delete‑char delete‑char‑or‑list delete‑horizontal‑space digit‑argument display‑shell‑version do‑lowercase‑version downcase‑word dump‑functions dump‑macros dump‑variables dynamic‑complete‑history edit‑and‑execute‑command emacs‑editing-mode end‑kbd‑macro end‑of‑history end‑of‑line exchange‑point‑and‑mark forward‑backward‑delete‑char forward‑byte forward‑char forward‑search‑history forward‑word glob‑complete‑word glob‑expand‑word glob‑list‑expansions history‑and‑alias‑expand‑line history‑expand‑line history‑search‑backward history‑search‑forward insert‑comment insert‑completions insert‑last‑argument kill‑line kill‑region kill‑whole‑line kill‑word magic‑space menu‑complete next‑history non‑incremental‑forward‑search‑history non‑incremental‑forward‑search‑history‑again non‑incremental‑reverse‑search‑history non‑incremental‑reverse‑search‑history‑again operate‑and‑get‑next overwrite‑mode possible‑command‑completions possible‑completions possible‑filename‑completions possible‑hostname‑completions possible‑username‑completions possible‑variable‑completions previous‑history quoted‑insert re‑read‑init‑file redraw‑current‑line reverse‑search‑history revert‑line set‑mark shell‑expand‑line start‑kbd‑macro tab‑insert tilde‑expand transpose‑chars transpose‑words tty‑status undo universal‑argument unix‑line‑discard unix‑word‑rubout upcase‑word self‑insert† vi‑append‑eol vi‑append‑mode vi‑arg‑digit vi‑bWord vi‑back‑to‑indent vi‑bword vi‑change‑case vi‑change‑char vi‑change‑to vi‑char‑search vi‑column vi‑complete vi‑delete vi‑delete‑to vi‑eWord vi‑editing‑mode vi‑end‑word vi‑eof‑maybe vi‑eword vi‑fWord vi‑fetch‑history vi‑first‑print vi‑fword vi‑goto‑mark vi‑insert‑beg vi‑insertion‑mode vi‑match vi‑movement‑mode vi‑next‑word vi‑overstrike vi‑overstrike‑delete vi‑prev‑word vi‑put vi‑redo vi‑replace vi‑search vi‑search‑again vi‑set‑mark vi‑subst vi‑tilde‑expand vi‑yank‑arg vi‑yank‑to yank yank‑last‑arg yank‑nth‑arg yank‑pop | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-p | Display Readline function names and bindings in such a way that they can be re‑read.
i.e."\C-y": yank | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-P | List current Readline function names and bindings in the format
# (if not bound, key-binding, function
example with only bound functions shown:
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-V | List current Readline variable names and values.
i.e.: blink-matching-paren on byte-oriented off completion-ignore-case off convert-meta on disable-completion off enable-keypad off expand-tilde off history-preserve-point off horizontal-scroll-mode off input-meta off mark-directories on mark-modified-lines off mark-symlinked-directories on match-hidden-files on meta-flag off output-meta off page-completions on prefer-visible-bell on print-completions-horizontally off show-all-if-ambiguous off visible-stats off bell-style audible comment-begin # completion-query-items 100 editing-mode vi keymap vi-insert |
for
, while
, until
, or
select
loop.
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
> 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'
ls /home/myname/webProject/index.html
.cd
if frequent access to another directory is needed. cd /home/myname/webProject
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. name
s 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 |
> 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_cwdUse
+
instead of -
to turn offsic the attribute . name
local, as with local
name
s is not a valid shell variable name
-f foo=bar
-f
.
/bin/echo
and there is printf
Output args
separated by spaces, terminated with a newline.
-n | no newline output (NOT zsh) |
-e | enable the interpretation of the special character codes. |
-E | no Enabling " … (default!) |
\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
#
begins a comment and stops the echo string, $
as usual.
-n
disable builtin shell command.
allowing a file command with that name without specifying a full pathname.test
firstenable -n test # i.e. disable the builtin test commandThis will most likely confuse you later! ed
With no options enable the builtin.
-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. % 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. name
is not a shell builtin or there is an error loading a new builtin from a shared object.
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. command
is specified, redirections may be used to affect the current shell environment.
n
,256) (default $?
Any
parent childscript.sh childScript.sh
ES=$?
if [ $ES -ne 0 ]
then echo "## childScript failed ES= $ES, I quit too!"; exit $ES
fi
… more parent stuff executed ifchildscript.sh
went well.
various commands
exit 4
trap on EXIT
is executed before the shell terminates.
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
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 name
s-f
name
is function; otherwise the name
s refer to variables.
-n
no longer mark each name
for export.
-p
output in a form that may be reused as input.
If no name
s 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 name
s 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
$HISTFILESIZE
$INPUTRC
$LIMITUSER
4LOCALLIBUSER
$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
hits command
1 /home2/reer1/.bin/df
1 /home2/reer1/.bin/du
10 /usr/bin/vim
1 /home2/reer1/.bin/stat
1 /home2/reer1/.bin/mysql
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.
Type `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 a match is displayed the return status is
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 0 is trapped and flagged as an error.
Operators are grouped in levels of equal-precedence , levels are listed in of decreasing precedence.
id++ , id-- |
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.
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 =
> echo $m
1231-1
> let x=$mmdd-1
> echo $x
1230
> n= 31
-bash: 31: command not found
(_) how to handle Jaunuary date? ie January 2011 does : 1101 - 1 = 1100 ; not the desired 1012 i.e. december 2010
name,
is created, and assigned value
.name
is supplied returns 1 .
funct(){ + local a=1 + echo $a + } >funct 1 >echo $a >
n
shell's parent.
printf
utility!
Write arguments
to standard output under control of format
,
a string which contains :
\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. format
is reused as necessary to process all arguments. format
specifies more arguments
than are supplied,
the extra format specifications behave as if a n
. .
† builtin,
returning either n
or
the exit status of the last command executed within the script as the exit status of the script.return
is used outside a function and not during the execution of a script by .
† .
exit
is for scripts.
read [-a aname] [-p prompt] [-er] [name … ]
One line is read from the standard input.
The characters in IFS
(which can be viewed using set |grep IFS |head -n 1
) are used to split the line into words.
The first word is assigned to the first $name
, the second word to the second $name
, …
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 name
s are supplied, the line is assigned to $REPLY
with tabs replaced by a single space.
The return code is 1
indicating the end-of-file was 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 reading input, if input is coming from a terminal.
-a aname words input are assigned to sequential indices of the array variable
| aname , starting at aname before the assignment. Other name arguments are ignored.
-e Readline is used to obtain the line.
| |
readarrray [-n count] [-O origin]
[-s count] [-t]
[-u file] [-C callback]
[-c quantum] [array]
Read lines from the standard input (or file
) into the indexed array variable array
, . mapfile
is the default array.
returns success (array
is readonly.
-c quantum | number of lines that have to be read between calls to the callback . The default 5000 !
|
-C callback | shell code. Outputs the index of the array that will be assigned, and the line is appended at evaluation time. |
-n count | maximun number of lines, Default 0, all. |
-O origin | Starts populatingi the array at origin rather than clearing it and starting at index |
-s count | skips count lines.
|
-t | trailing newline s are removed |
-u file | rather than standard input. |
name
as readonly, the values may not be changed by subsequent assignment.
The return status is 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 [--abefhkmnptuvxBCHP] [-o option] [argument …]setsname to value . Not in zsh
Without options, displays names and values of variables and functions (with their definition which can be lenghty)
in a format that may be reused as input. BASH=/bin/bash BASH_ARGC=() BASH_ARGV=() BASH_LINENO=() BASH_REMATCH=([0]="n") BASH_SOURCE=() BASH_VERSINFO=([0]="3" [1]="2" [2]="57" [3]="1" [4]="release" [5]="x86_64-apple-darwin15") BASH_VERSION='3.2.57(1)-release' BLOCKSIZE=1k COLUMNS=140 DIRSTACK=([0]="~" [1]="/Volumes/homes/sams/Documents/computerstuff/firmware" [2]="/Volumes/DATA/homes/sams/bin") EUID=531 … GROUPS=() … HOME=/Users/samspade … HOSTNAME=venus HOSTTYPE=x86_64 IFS=$' \t\n' LANG=en_US.UTF-8 LC_ALL=C … … …in a format that can be reused as input for setting or resetting the currently-set variables. Read-only variables cannot be reset. In posix mode, only shell variables are listed. The output is sorted according to the current locale. When options are specified, they set or unset shell attributes. Any arguments remaining after the options are processed are treated as values for the positional parameters and are assigned, in order, to $1, $2, ... $n.
|
+
turns the option offsic. name
is removed. name
is a variable. name
refers to functions, and the definition is removed.
For bash
options +
(rather than -
) causes the option to be turned offsic.
Current bash
options are in $-
.
> echo $-
himBH
The remaining N argument
s are positional parameters assigned to $1
,
$2
, … $N
. $#
is set to N.$1
to $2
…
see export
set -o option-name [on| off ]
Set the option corresponding to option-name
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
| ||||||||||||||||||||||||||||||||||||||
-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 .
| ||||||||||||||||||||||||||||||||||||||
emacs | Use emacs -style line editing interface (see readline).
| |||||||||||||||||||||||||||||||||||||||
vi
| Use a vi -style line editing interface.
> set -o vi | |||||||||||||||||||||||||||||||||||||||
history | Enable command history. | |||||||||||||||||||||||||||||||||||||||
-H | histexpand Enable | ! style history substitution
(History Expansion). Default on for interactive shells.
-p | privileged Turn on privileged mode. | | | ignoreeof An interactive shell will not exit upon reading EOF.
| | | posix POSIX Mode
|
|
> 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
See : shopt
, bash variables,invoking bash.
n
(default: 1)
renaming them from $n
+1 to $1
… and
reducing $#
by n.
n+1
through $#
are unset and the return status is n
must ≥ $#
.Display the list if no options specified:
cdable_vars off cdspell off checkhash off checkwinsize off cmdhist on dotglob 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 option 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 |
source filename
A synonym for .
( dot )
0m0.060s 0m0.260s 0m1.250s 0m2.240s
The return status is
If a command begins with time
the elapsed, user and system time consumed by its execution are reported when the pipeline terminates.
The0.0 wall time; 0.012 user; 0.009 sys; 59.06%
-p
option changes the output format to that specified by POSIX.
Thereal 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. l
onger format, including minutes, MMmSS.FFs. real
\t%3lR
\nuser
\t%3lU
\nsys
\t%3lS
time
is not recognized if the next token begins with a -
.
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. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
KILL
issued to a process in a wait
will cause the wait
to expire immediately.kill
-signal PID remain pending if
the script is processing a wait
, until the wait
expires!
sigspec
is not a valid signal.
Example: remove tmp files and exit with a return code of 2 when the terminal user presses ^c
trap "rm -f /tmp/${TMP}*; exit 2" SIGint
To make a script "safe" by limiting the execution time and filespace it can use and
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 -p # show set traps
trap -- 'echo good bye ' EXIT > logout good bye Connection to real-world-systems.com closed.
--afPt†pa
]
[name
…]
For each name
, display how it would be interpreted as a command.
-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 |
-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) |
-c | core files space used(seperate from other files). |
-n | number of open file descriptors. |
-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 |
-u | number of user processes |
-p | pipe buffer size. ( 512 byte blocks) |
A Soft limit can be changed up to the maximum set by the hard limit.
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 .
Examples:
ulimit -f 2
ulimit -t 3
When the total CPU time reaches 3 seconds
Cputime limit exceeded: 24
> tar -cf t *
File size limit exceeded (core dumped)
see trap
The return status is 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 permittedAnd returns a status of 1.
-S |
Evaluate a conditional expression.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
In this example -exists should be | |||||||||||||
|
Example:
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 $rcSimilarily 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>
try_to_do_stuff && do_more_stuff_since_it_is_going_well
try_to_do_stuff || clean_up_mess_from_failured_stuff
used by
if
command.
-bash: [: -eq: unary operator expected
Is reported when attempting to compare an unset $variable.
Expressions may be unary or binary†.
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 |
String compares are not the same as numeric.
Results in red may not be as expceted:
> if [ 01 == 1 ]; then echo EQUAL; else echo NO ; fi
NO
(==
does a string compare)
> if [ "01" -eq 1 ]; then echo EQUAL; else echo NO ; fi
EQUAL
(-eq
does a numeric compare)
> if [ 01 -eq 1 ]; then echo EQUAL; else echo NO ; fi
EQUAL
> if [ "1" == 1 ]; then echo EQUAL; else echo NO ; fi
EQUAL
> if [ "1" -eq 1 ]; then echo EQUAL; else echo NO ; fi
EQUAL
> if [ 1 ]; then echo TRUE ;fi
TRUE
> if [ 0 ]; then echo TRUE ;fi
TRUE
Don't use to test for null argument see ParamExpansions
The status of a file† can be checked with:
-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 andrefers 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)
If any 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.
these
>>>>??? -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. code>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, greater-than, or greater-than-or-equali
than arg2
.
Exit Status:
Returns success if EXPR evaluates to true; fails if EXPR evaluates to false or an invalid argument is given.
Testing if an environmental variable has a value by
concatenat command with x; check against null.
if [ "$VAR"x = ""x ] ; then …
See expansion "${1:-}"
to test function argument.
Arithmetic expressions are be evaluated by let
> let i=$j+4 ; echo $i #or as a shell expansion.no spaces! 12
> echo $((13/6)) 2
Evaluation is done in long integers with no check for overflow.
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,
+ -
| 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' |
Variables are allowed as operands.
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.
Constants with a leading 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.
Operators are evaluated in order of precedence.
Sub-expressions in parentheses are evaluated first.
Array varriables are one-dimensional, zero-based and
are created using
declare -a name
or
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.
Arrays are assigned using compound assignments of the form 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.
Elements of an array are referenced using ${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.
echo $DIRS
pushd | adds entries to the stack as it changes the current directory, | ||||||||||||||
popd | removes entries from the stack and changes the current directory to the directory removed. | ||||||||||||||
dirs | displays the directory stack, or current directory if stack is empty!
|
The directory stack is the array $DIRSTACK
.
set|grep DIRS DIRSTACK=([0]="~" [1]="/Volumes/homes/sams/Documents/computerstuff/firmware" [2]="/Volumes/DATA/homes/sams/bin")
dirs [+N | -N] [-clvp]
pushd [dir | +N | -N] [-n]Save the current directory on the top of the directory stack and then
cd
to dir
, then displays stack. 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 cd s 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
Usepopd -n
to remove an invalid entry./home/reer1/www/docs > /home/reer1/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/docsSee cd Bash executesPROMPT_COMMAND
before printing$PS1
or$PS2
(used when for continuation lines)Special characters used in the prompt :
Example including 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 '
\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 like terminal control sequences for example colors \]
End sequence
\[\e[32m\]\u@\h\[\e[00m\]:\[\e[34m\]\w \$\[\e[00m\]
pi@JEBH
:
/home/pi