//a side-by-side reference sheet//

[#grammar-execution grammar and execution] | [#var-expr variables and expression] | [#arithmetic-logic arithmetic and logic] | [#strings strings] | [#regexes regexes] | [#dates-time dates and time] | [#arrays arrays] | [#functions functions] | [#execution-control execution control] | [#exceptions exceptions] | [#streams streams] | [#files files] | [#directories directories] | [#processes-environment processes and environment] | [#libraries-namespaces libraries and namespaces] | [#reflection reflection] | [#debugging-profiling debugging and profiling]

||~ # general||~ [#posix posix shell]||~ [#cmd-prompt cmd.exe]||~ [#powershell powershell]|| ||# version-used[#version-used-note version used] _ @< >@||##gray|//dash; POSIX 2008//##||##gray|//6.3//##||##gray|//4.0//##|| ||# version[#version-note show version] _ @< >@|| ||##gray|//displayed at startup//##||$host.version|| ||||||||~ # grammar-execution[#grammar-execution-note grammar and execution]|| ||~ ||~ [#posix posix shell]||~ [#cmd-prompt cmd.exe]||~ [#powershell powershell]|| ||# interpreter[#interpreter-note interpreter] _ @< >@||$ dash foo.sh||##gray|//when foo.bat is in the search path://## _ @@>@@ foo||@@PS>@@ .\foo.ps1 _ _ @@DOS>@@ powershell -file foo.ps1|| ||# repl[#repl-note repl] _ @< >@||$ dash||@@>@@ cmd||@@>@@ powershell|| ||# exec-and-exit[#exec-and-exit-note execute command and exit]||$ dash -c ‘echo hi’||@@>@@ cmd /c “echo hi”||@@>@@ powershell -command ‘write-output “hi”’|| ||# stmt-separator[#stmt-separator-note statement separator]||##gray|//pipelines separated by//## _ ; & && @@||@@ _ _ ##gray|//lists of pipelines separated by newlines unless newline is preceded by a backslash or inside these characters://## _ ““ ‘‘ @@@@ ()||##gray|//pipelines separated by//## & && @@||@@ _ _ ##gray|//lists of pipelines separated by newline unless preceded by caret ^ which is not inside double quote "//##||; ##gray|//or newline; a newline can be escaped with a backtick://## @@`@@ ##gray|//newlines are permitted in double quotes and after a pipe://## | || ||[# word-separator](%23%20word-separator.html)[#word-separator-note word separators]|| | & ; ( ) < > ##gray|//space tab//##|| | & < > ##gray|//space tab//##|| || ||[# esc-special-char](%23%20esc-special-char.html)[#esc-special-char-note escape special character]||##gray|# write "foo" to foo.txt:## _ echo foo > foo.txt _ _ ##gray|# write "foo > foo.txt" to stdout:## _ echo foo \> foo.txt||##gray|rem write "foo" to foo.txt## _ echo foo > foo.txt _ _ ##gray|rem write "foo > foo.txt" to stdout:## _ echo foo ^> foo.txt|| || ||[# block-delimiters](%23%20block-delimiters.html)[#block-delimiters-note block delimiters]||{##gray|//...//##} _ (##gray|//...//##) _ do ##gray|//...//## done||( ##gray|//...//## )||{ ##gray|//...//## }|| ||[#expression-statement are expressions statements]||##gray|//no//##||##gray|//no _ _ relational expressions can only be used in the conditional of an// if //statement _ _ arithmetic expressions can only be assigned to a variable using// set /a##||##gray|//yes//##|| ||[# comment](%23%20comment.html)[#comment-note end-of-line comment] _ @<&nbsp;>@|| # ##gray|//comment//##|| rem ##gray|//comment//## _ _ :: ##gray|//comment//##||# ##gray|//comment//##|| ||[# multiline-comment](%23%20multiline-comment.html)[#multiline-comment-note comment out multiple lines]||@@<<@@EOF _ ##gray|//comment//## _ ##gray|//another comment//## _ EOF||goto comment _ ##gray|//comment//## _ ##gray|//another comment//## _ :comment||<# ##gray|//comment//## _ ##gray|//another comment//## #>|| ||||||||~ [# var-expr](%23%20var-expr.html)[#var-expr-note variables and expressions]|| ||~ ||~ [#posix posix shell]||~ [#cmd-prompt cmd.exe]||~ [#powershell powershell]|| ||[# assignment](%23%20assignment.html)[#assignment-note assignment]||a=1 _ ##gray|//whitespace next to//## = ##gray|//not permitted//##||set a=1||$a = 1|| ||[# parallel-assignment](%23%20parallel-assignment.html)[#parallel-assignment-note parallel assignment] _ @<&nbsp;>@||##gray|//none//##||##gray|//none//##||$a, $b = 1, 2|| ||[# swap](%23%20swap.html)[#swap-note swap]||tmp=$a _ a=$b _ b=$tmp||set tmp=%a% _ set a=%b% _ set b=%tmp%||$a, $b = $b, $a|| ||[# compound-assignment](%23%20compound-assignment.html)[#compound-assignment-note compound assignment operators: arithmetic, string, bit]||##gray|//none//##||+= -= *= /= %= _ ##gray|//none//## _ <<= >>= &= |= ^=||+= -= *= /= %= _ += *= _ ##gray|//none//##|| ||[# incr-decr](%23%20incr-decr.html)[#incr-decr-note increment and decrement]||##gray|//none//##||##gray|//none//##||$x = 1 _ $x@@++@@ _ $x@@--@@|| ||[# var-decl](%23%20var-decl.html)[#var-decl-note variable declaration] _ @<&nbsp;>@||##gray|//assignment//##, export, readonly||##gray|//assignment//##||##gray|//assignment//##|| ||[# identifiers-case-sensitive](%23%20identifiers-case-sensitive.html)[#identifiers-case-sensitive-note are identifiers case sensitive?]||##gray|//yes//##||##gray|//no//##||##gray|//no//##|| ||[# null](%23%20null.html)[#null-note null] _ @<&nbsp;>@||''||##gray|//Variables must contain a non-empty string. This deletes the variable x://## _ set x=||$null|| ||[# null-test](%23%20null-test.html)[#null-test-note null test] _ @<&nbsp;>@||if [ -z $v ] _ then _ @<&nbsp;&nbsp;>@echo not defined _ fi||if not defined v echo not defined||$v -eq $null|| ||||||||~ [# arithmetic-logic](%23%20arithmetic-logic.html)[#arithmetic-logic-note arithmetic and logic]|| ||~ ||~ [#posix posix shell]||~ [#cmd-prompt cmd.exe]||~ [#powershell powershell]|| ||[# true-false](%23%20true-false.html)[#true-false-note true and false] _ @<&nbsp;>@||##gray|//status codes://## _ true false _ _ ##gray|//inside// [ ]:## _ 1 ''||##gray|//no booleans; conditional of if statement must contain a relational expression//##||$true $false|| ||[# falsehoods](%23%20falsehoods.html)[#falsehoods-note falsehoods]||##gray|//status codes: _ nonzero integers//## _ _ ##gray|//inside// [ ]:## _ ''||##gray|//relational expressions which evaluate to false//##||0 0.0 "" ''|| ||[# logical-ops](%23%20logical-ops.html)[#logical-ops-note logical operators] _ @<&nbsp;>@||##gray|//status codes://## _ && @@||@@ ! _ _ ##gray|//inside// [ ]:## _ -a -o ! ||##gray|//short-circuit operators://## _ && @@||@@ _ _ ##gray|//inside conditional of if://## _ not||-and -or -not|| ||[# conditional-expr](%23%20conditional-expr.html)[#conditional-expr-note conditional expression] _ @<&nbsp;>@||$(( x>0 ? x : -x ))||##gray|//none//##||##gray|//none//##|| ||[#relational-expr relational expression] _ @<&nbsp;>@||[ $a -gt 3 ]||%a% gtr 3||$a -gt 3|| ||[#relational-operators relational operators] _ @<&nbsp;>@||##gray|//integers://## _ -eq -ne -gt -lt -ge -le _ _ ##gray|//strings://## _ @@=@@ != > < ##gray|//none//## ##gray|//none//##||equ neq gtr lss geq leq||-eq -ne -gt -lt -ge -le|| ||[#arithmetic-expr arithmetic expression] _ @<&nbsp;>@||$(( 1 + 3 ))||##gray|//arithmetic expression must be stored in a variable://## _ set /a "foo=1+3"||1 + 3|| ||[#arithmetic-operators arithmetic operators] _ @<&nbsp;>@||+ - * ##gray|//none//## / % @@**@@ _ _ ##gray|//operators are integer-only in most shells; use// bc //for float arithmetic//##||+ - * ##gray|//none//## / % ##gray|//none//## _ _ ##gray|//operators only work on integers//##||+ - * / ##gray|//??//## % ##gray|//??//##|| ||[#integer-division integer division] _ @<&nbsp;>@||$(( $a / $b ))||set /a "result=7/3"||$rem = $null _ $quot = [Math]::DivRem($a, $b, [ref] $rem)|| ||[# int-div-zero](%23%20int-div-zero.html)[#int-div-zero-note integer division by zero]||##gray|//writes "division by 0" error message; statement terminates with a 1 status//##||##gray|//Writes "Divide by zero error." and sets %errorlevel% to nonzero value.//##||##gray|//error: Attempted to divide by zero//##|| ||[#float-division float division] _ @<&nbsp;>@||@@`@@echo " scale=5; $a / $b " | bc@@`@@||##gray|//none//##||$a / $b|| ||[# float-div-zero](%23%20float-div-zero.html)[#float-div-zero-note float division by zero]||##gray|//writes "division by 0" error message; statement terminates with a 1 status//##||##gray|//none//##||##gray|//evaluates to// Infinity //which is not a float literal//##|| ||[# power](%23%20power.html)[#power-note power] _ @<&nbsp;>@|| ||##gray|//none//##||[Math]::pow(2, 32)|| ||[# sqrt](%23%20sqrt.html)[#sqrt-note sqrt] _ @<&nbsp;>@|| ||##gray|//none//##||[Math]::sqrt(2)|| ||[#sqrt-negative-two sqrt -2] _ @<&nbsp;>@||##gray|//no sqrt//##||##gray|//none//##||##gray|//evaluates to// NaN //which is not a float literal//##|| ||[#transcendental-func transcendental functions]||e l s c ##gray|//none//## ##gray|//none//## ##gray|//none//## a ##gray|//none//## _ ##gray|//how to use://## _ @@`@@echo 'e(2)' | bc -l@@`@@||##gray|//none//##||[Math]::exp [Math]::log _ [Math]::sin [Math]::cos [Math]::tan _ [Math]::asin [Math]::acos [Math]::atan _ ||[#float-truncation float truncation] _ ##gray|//round towards zero, round to nearest integer, round down, round up//##||##gray|//none and no floats//##||##gray|//none//##||[Math]::truncate(3.14) _ [Math]::round(3.14) _ [Math]::floor(3.14) _ ||[# abs-val](%23%20abs-val.html)[#abs-val-note absolute value] _ ##gray|//and signum//##|| ||##gray|//none//##||[Math]::abs(-7) _ ||[#integer-overflow integer overflow] _ @<&nbsp;>@||##gray|//modular arithmetic//##||##gray|//sometimes modular arithmetic; sometimes writes error message and sets %errorlevel% to nonzero value.//##||##gray|//converts to float//##|| ||[#float-overflow float overflow] _ @<&nbsp;>@||##gray|//no floats//##||##gray|//none//##||##gray|//evaluates to// Infinity //which is not a float literal//##|| ||[#random random integer, uniform float]||echo $RANDOM ##gray|//15 bit integer//##||##gray|rem integer in range 0 to 32767:## _ echo %random%||random 100 _ random 1.0|| ||[#seed-random seed random numbers]||RANDOM=17 _ r=$RANDOM||##gray|//none//##||$r = random -setseed 17|| ||[#bit-operators bit operators] _ @<&nbsp;>@||@<<< >> & | ^ ~>@||##gray|//use with// set /a:## _ @<<< >> & | ^ ~>@||##gray|//none//## ##gray|//none//## -band -bor -bxor -bnot _ _ ##gray|# powershell 3.0:## _ -lsl -lsr|| ||||||||~ [# strings](%23%20strings.html)[#strings-note strings]|| ||~ ||~ [#posix posix shell]||~ [#cmd-prompt cmd.exe]||~ [#powershell powershell]|| ||[#string-literal string literal]||'don'\''t say "no"' _ "don't say \"no\"" _ $'don\'t say "no"'||##gray|//None; barewords are used for strings.//## _ _ ##gray|//Double quotes are used for file names which contain spaces and other special characters. However, the double quotes are stored in the variables and passed to commands.//##||'don''t say "no"' _ "don't say @@`@@"no@@`@@""|| ||[#string-literal-newline newline in literal]||##gray|//yes//##||##gray|//No; a bareword string can be continued on the following line by ending a line with ^; the CRLF is not part of the value of the string; it is not possible to store a CRLF in a variable.//##||##gray|//yes//##|| ||[#barewords barewords]||##gray|//yes//##||##gray|//yes//##||##gray|//yes//##|| ||[# bareword-esc-char](%23%20bareword-esc-char.html)[#bareword-esc-char-note bareword escape character]||##gray|//backslash://## \;||##gray|//caret://## ^< _ _ ##gray|//Characters special to the interpreter can be stored in a variable by preceding them by a caret: ^; the interpreter will attempt to interpret them when the variable is dereferenced, however.//##||##gray|//backquote://: @@`@@$|| ||[#string-escapes escapes]||##gray|//in double quotes//## _ \\ \" _ ##gray|//in//## $' ' ##gray|//quotes://## _ \a \b \e \f \n \r \t \v \\ \' \c##gray|//c//## \x##gray|//hh//## \##gray|//ooo//##|| ||@@`@@' @@`@@" @@@@ _ @@@@0 @@@@a @@@@b @@@@f @@@@n @@@@r @@@@t @@@@v _ ##gray|//in other backtick sequences the backtick is ignored//##|| ||[#variable-interpolation variable interpolation]||count=3 _ item=ball _ “$count ${item}s”|| ||$count = 3 _ $item = “ball” _ “$count $($item)s”|| ||[#string-length length]||s="hello” _ ${#s}||##gray|//see footnote//##||$s = “hello” _ $s.length|| ||[#string-comparison string comparison]||[ $USER = foo ] _ [ $USER != foo ]|| ||##gray|# case insensitive:## _ -eq -ne -gt -lt -ge -le _ _ ##gray|# case sensitive:## _ -ceq -cne -cgt -clt -cge -cle|| ||[#index-substring index of substring]||##gray|//none//##|| ||##gray|//returns -1 if not found://## _ “foo bar”.indexof(“bar”)|| ||[#extract-substring extract substring]||s="foo bar” _ ${s:4:3}||set s=foo bar _ echo %s:~4:3%||"foo bar”.substring(4, 3)|| ||[#string-concatenation string concatenation]||c="hello, ““world”||##gray|rem trailing whitespace is stored:## _ set part1=hello,@< >@ _ set part2=world _ echo %part1%%part2%||$c = “hello, “ + “world”|| ||[#string-replication string replication]|| || ||$hbar = “-” * 80|| ||[#split split]||##gray|//none//##|| ||"foo,bar,baz” -split “,”|| ||[#join join]||##gray|//none//##|| ||@(“foo”,"bar”,"baz”) -join “,”|| ||[#sprintf sprintf]||@@@@printf "tie: %s %d %f" "Spain" 13 3.7@@@@|| ||$a = “Spain”, 13, 3.7 _ “tie: {0} {1} {2}” -f $a|| ||[#case case manipulation]||echo “hello” | tr [a-z] [A-Z] _ echo “HELLO” | tr [A-Z] [a-z] _ A=hello _ echo -n ${A:0:1} | tr [a-z] [A-Z]; echo -n ${A:1}|| ||"hello”.toupper() _ “HELLO”.tolower()|| ||[#strip strip]||##gray|//none//##|| ||” hello “.trim()|| ||[#pad pad on right, pad on left]||@@@@printf "%-10s" "hello"@@@@ _ @@@@printf "%10s" "hello"@@@@|| ||$s = “hello” _ $s + “ “ * (10 - $s.length) _ “ “ * (10 - $s.length) + $s|| ||[#string-to-number string to number]||A="12” _ $(( 7 + $A )) _ _ B=”.037” _ @@@@echo 73.9 + $B | bc@@@@||set x="12” _ set /a “result=7+%x%”||7 + “12” _ _ 73.9 + “.037”|| ||[#number-to-string number to string] _ @< >@||##gray|//all values are strings//##||##gray|//all values are strings//##||[convert]::tostring(7) + “ items” _ _ ##gray|# or use variable interpolation##|| ||||||||~ # regexes[#regex-note regular expressions]|| ||~ ||~ [#posix posix shell]||~ [#cmd-prompt cmd.exe]||~ [#powershell powershell]|| ||# regex-match[#regex-match-note regex match]||s=hello _ rx=’[a-z][a-z]’ _ if expr $s : $rx > /dev/null _ then _ @<  >@##gray|//…//## _ fi||set s=hello _ echo %s%|findstr /r “[a-z][a-z]” && (echo match ) ^ _ @<  >@@@||@@ (echo does not match)||if (“hello” -match “^[a-z][a-z]*$”) { _ @<  >@##gray|//…//## _ }|| ||# single-subst[#single-subst-note single substitution]||s=’do re mi mi mi’ _ s=$(echo $s | sed s/mi/ma/)|| || || ||# global-subst[#global-subst-note global substitution]||s=’do re mi mi mi’ _ s=$(echo $s | sed s/mi/ma/g)||set “s=do re mi mi mi” _ echo %s:mi=ma%||$s = “do re mi mi mi” _ $s = $s -replace “mi”, “ma”|| ||||||||~ # dates-time[#dates-time-note dates and time]|| ||~ ||~ [#posix posix shell]||~ [#cmd-prompt cmd.exe]||~ [#powershell powershell]|| ||# current-datetime[#current-datetime-note current datetime]||date +’%Y-%m-%d %H:%M:%S’||date /t && time /t||get-date -format ‘yyyy-MM-dd HH:mm:ss’ _ get-date -uformat ‘%Y-%m-%d %H:%M:%S’|| ||# current-unix-epoch[#current-unix-epoch-note current unix epoch]||date +’%s’|| ||get-date -uformat %s|| ||# fmt-datetime[#fmt-datetime-note format datetime]||date -d ‘1970-01-01 00:00:00 UTC’ +’%s’|| ||get-date -date ‘1970-01-01 00:00:00’ -uformat %s|| ||||||||~ # arrays[#arrays-note arrays]|| ||~ ||~ [#posix posix shell]||~ [#cmd-prompt cmd.exe]||~ [#powershell powershell]|| ||# resizable-array-literal[#resizable-array-literal-note literal]||nums=(1 2 3 4)||set nums=(1 2 3 4)||$nums = 1 ,2 ,3, 4 _ $nums = @(1 ,2, 3, 4)|| ||# resizable-array-size[#resizable-array-size-note size]||${#nums[@]}||set numsc=0 _ for %i in %nums% do set /a numsc+=1 _ echo %numsc%||$nums.Length|| ||# resizable-array-lookup[#resizable-array-lookup-note lookup] _ @< >@||${nums[0]}|| ||$nums[0]|| ||# resizable-array-update[#resizable-array-update-note update] _ @< >@||nums[1]=5|| ||$nums[0] = 5|| ||[#array-slice slice] _ @< >@||${nums[@]:1:2}|| ||$nums[1..2]|| ||[#array-concatenation concatenate]||a=(1 2 3) _ b=(4 5 6) _ c=(${a[@]} ${b[@]})|| ||@(1, 2, 3) + @(4, 5, 6)|| ||[#array-iteration iterate over elements]||for i in ${nums[@]} _ do echo $i _ done|| ||foreach ($i in $nums) { _ @<  >@write-output $i _ }|| ||[#array-sort sort]|| || ||$a = 3, 2, 4, 1 _ $b = $a | Sort-Object|| ||[#array-reverse reverse]|| || ||$a = 1, 2, 3 _ ||||||||~ # functions[#functions-note functions]|| ||~ ||~ [#posix posix shell]||~ [#cmd-prompt cmd.exe]||~ [#powershell powershell]|| ||# def-func[#def-func-note define]||add() { echo $(( $1 + $2 )); } _ ##gray|//or//## _ function add { echo $(( $1 + $2 )); }||goto:eof _ :add _ @<  >@set /a sum=%1+%2 _ @<  >@echo %sum% _ goto:eof||function add { _ @<  >@param ($a, $b) _ @<  >@$a + $b _ }|| ||# call-func[#call-func-note call] _ @< >@||add 1 2||call:add 1 2||add 1 2|| ||# missing-arg[#missing-arg-note missing argument behavior]||’’||##gray|//parameter treated as undefined variable or as containing the empty string//##||$null|| ||# extra-arg[#extra-arg-note extra argument behavior]||##gray|//ignored//##||##gray|//none//##||##gray|//ignored//##|| ||# default-arg[#default-arg-note default argument]||##gray|//none//##||##gray|//none//##||function add { _ @<  >@param ($a=0, $b=0) _ @<  >@$a + $b _ }|| ||# named-param[#named-param-note named parameters]||##gray|//none//##||##gray|//none//##||add -a 1 -b 2|| ||# retval[#retval-note return value]||return ##gray|//arg available in//## $? ##gray|//variable if a positive integer smaller than 256//##|| || || ||# anon-func-literal[#anon-func-literal-note anonymous function literal]||##gray|//none//##||##gray|//none//##||$f = { write-output “foo” }|| ||# call-anon-func[#call-anon-func-note call anonymous function]||##gray|//none//##||##gray|//none//##||& $f _ ##gray|//or//## _ $x.invoke()|| ||[#default-scope default scope] _ @< >@||##gray|//global//##||##gray|//global//##||##gray|//local//##|| ||# nest-func[#nest-func-note nest]||##gray|//Nested function visible outside containing function.//##||##gray|//none//##||function add { _ @<  >@param ($a, $b) _ @<  >@function add2 { _ @<  >@@<  >@param ($a2, $b2) _ @<  >@@<  >@$a2 + $b2 _ @<  >@} _ @<  >@add2 $a $b _ } _ _ ##gray|# Nested function not visible outside of containing _

function; nested function can see local variables _

of containing function.##||

||||||||~ # execution-control[#execution-control-note execution control]|| ||~ ||~ [#posix posix shell]||~ [#cmd-prompt cmd.exe]||~ [#powershell powershell]|| ||# if[#if-note if]||if [ $n -eq 0 ] _ then _ @<  >@echo “no hits” _ elif [ $n -eq 1 ] _ then _ @<  >@echo “1 hit” _ else _ @<  >@echo $n “ hits” _ fi||if %n% equ 0 ( _ @<  >@echo no hits _ ) else ( _ @<  >@if %n% equ 1 ( _ @<  >@@<  >@echo one hit _ @<  >@) else ( _ @<  >@@<  >@echo %n% hits _ @<  >@) _ )||if ($n -eq 0) { _ @<  >@write-output “no hits” _ } elseif ($n -eq 1) { _ @<  >@write-output “one hit” _ } else { _ @<  >@write-output “$n hits” _ }|| ||# while[#while-note while]||i=0 _ while [ $i -lt 10 ] _ do i=$(($i + 1)) _ @<  >@echo $i _ done||set i=0 _ :loop _ @<  >@set /a i+=1 _ @<  >@echo %i% _ if %i% lss 10 goto :loop||$i = 0 _ while ($i -lt 10) { _ @<  >@write-output (++$i) _ }|| ||# for[#for-note for]||for i in 1 2 3 _ do _ @<  >@echo $i _ done||set nums=(1 2 3 4) _ for %%n in %nums% do echo %%n||for ($i=1; $i -le 3; $i++) { _ @<  >@write-output $i _ }|| ||# break[#break-note break] _ @< >@||break|| ||break|| ||# continue[#continue-note continue] _ @< >@||continue|| ||continue|| ||||||||~ # exceptions[#exceptions-note exceptions]|| ||~ ||~ [#posix posix shell]||~ [#cmd-prompt cmd.exe]||~ [#powershell powershell]|| ||# raise-exc[#raise-exc-note raise]||##gray|//Commands which fail return nonzero exit status. _ _ Exit status of last command stored in $?//##||##gray|//Commands which fail return nonzero exit status. _ _ Exit status of last command stored in %errorlevel%//##||throw “bam!”|| ||# handle-exc[#handle-exc-note handle]||trap ‘echo “risky failed”’ ERR _ risky||risky _ _ if errorlevel 1 ( _ @<  >@echo risky failed _ )||try { _ @<  >@throw “bam!” _ } _ catch { _ @<  >@write-output “caught!” _ }|| ||# uncaught-exc[#uncaught-exc-note uncaught exception behavior]||##gray|//stderr and continue//##||##gray|//stderr and continue//##||##gray|//script exits//##|| ||||||||~ # concurrency[#concurrency-note concurrency]|| ||~ ||~ [#posix posix shell]||~ [#cmd-prompt cmd.exe]||~ [#powershell powershell]|| ||# sleep[#sleep-note sleep]||sleep 10||##gray|//vista and later://## _ timeout 10||timeout 10|| ||||||||~ # streams[#streams-note streams]|| ||~ ||~ [#posix posix shell]||~ [#cmd-prompt cmd.exe]||~ [#powershell powershell]|| ||# read-line-stdin[#read-line-stdin-note read line from stdin]||##gray|# stored in $ine:## _ read line _ _ ##gray|# with prompt:## _ read -p ‘line: ‘ line||##gray|rem stored in %line%:## _ set /p line= _ _ ##gray|rem with prompt:## _ set /p line="line: “||$line = read-host _ _ ##gray|# with prompt:## _ $line = read-host ‘line’|| ||# write-line-stdout[#write-line-stdout-note write line to stdout]||echo “hi world”||echo hi world||write-output “hi world”|| ||# printf[#printf-note write formatted string to stdout]||printf ‘%.2f\n’ 3.1415|| || || ||# write-file-stdout[#write-file-stdout-note write file to stdout]||cat foo.txt|| || || ||# write-stderr[#write-stderr-note write to standard error]||echo “hi world” >&2||echo hi world >&2|| || ||# file-iterate[#file-iterate-note iterate over file by line]||awk ‘length($0) > 70 {print $0}’ /etc/passwd|| || || ||# write-proc[#write-proc-note write to process]||echo “hi world” | wc||echo hi world | find /c hi|| || ||[#write-file write to file]||echo “hello” > /tmp/a||echo hello > \tmp\a|| || ||[#append-file append to file]||echo “hello” @@>>@@ /tmp/a||echo hello @@>>@@ \tmp\a|| || ||||||||~ # files[#files-note files]|| ||~ ||~ [#posix posix shell]||~ [#cmd-prompt cmd.exe]||~ [#powershell powershell]|| ||# create-empty-file[#create-empty-file-note create empty file]||##gray|# does not overwrite existing file, but updates _

last mod. time:## _

touch foo.txt||##gray|rem overwrites existing file:## _ type nul > foo.txt||##gray|# error if file exists:## _ new-item -type file foo.txt|| ||# file-test[#file-test-note file exists test, file regular test]||if [ -e foo.txt ]; then echo “exists”; fi _ if [ -f foo.txt ]; then echo “regular”; fi||if exist foo.txt ( echo exists ) _ _ ##gray|//??//##||if (test-path foo.txt) { write-output “exists” } _ _ if (test-path -pathtype leaf) { _ @<  >@write-output “regular” _ }|| ||# file-size[#file-size-note file size]||ls -l foo.txt||dir foo.txt||get-childitem foo.txt|| ||# readable-writeable-executable[#readable-writeable-executable-note is readable, is writeable, is executable]||if [ -r /etc/passwd ]; then echo readable; fi _ if [ -w /tmp ]; then echo writeable; fi _ if [ -x /bin/ls ]; then echo executable; fi|| || || ||# chmod[#chmod-note set file permisions]||chmod 0600 foo.txt|| || || ||# last-modification-time[#last-modification-time-note last modification time]||ls -l foo.txt||dir foo.txt||get-childitem foo.txt|| ||# file-cp-rm-mv[#file-cp-rm-mv-note copy file, remove file, rename file]||cp /tmp/foo.txt /tmp/bar.txt _ rm /tmp/foo.txt _ mv /tmp/bar.txt /tmp/foo.txt||copy foo.txt bar.txt _ del foo.txt _ move bar.txt foo.txt||copy-item foo.txt bar.txt _ remove-item foo.txt _ move-item bar.txt foo.txt|| ||# symlink[#symlink-note create symlink, symlink test, readlink]||ln -s /etc/passwd /tmp/passwd _ if [ -h /tmp/passwd ]; then echo “symlink”; fi _ readlink /tmp/passwd|| || || ||# unused-file-name[#unused-file-name-note generate unused file name]||mktemp /tmp/fooXXXXX|| || [System.IO.Path]::GetTempFileName()|| ||||||||~ # directories[#directories-note directories]|| ||~ ||~ [#posix posix shell]||~ [#cmd-prompt cmd.exe]||~ [#powershell powershell]|| ||# working-dir[#working-dir-note working directory] _ ##grey|//get and set//##||echo $(pwd) _ echo $PWD _ _ cd /tmp||echo %cd% _ _ chdir \windows||$loc = get-location _ echo $loc _ _ set-location \windows|| ||# program-dir[#program-dir-note program directory]||##gray|//bash only://## _ “$( cd “$( dirname “${BASH_SOURCE[0]}” )” && pwd )”||echo %~dp0|| || ||# direname-basename[#dirname-basename-note dirname and basename]||dirname /etc/hosts _ basename /etc/hosts|| || || ||# iterate-dir[#iterate-dir-note iterate over directory by file]||for f in /etc/* _ do _ @<  >@echo $f _ done|| || || ||# mkdir[#mkdir-note make directory]||mkdir /tmp/foo.d||mkdir foo||new-item -type directory foo|| ||# recursive-cp[#recursive-cp-note recursive copy]||cp -R /tmp/foo.d /tmp/bar.d|| || || ||# rmdir[#rmdir-note remove empty directory]||rmdir /tmp/foo.d||rmdir foo|| || ||# rm-rf[#rm-rf-note remove directory and contents]||rm -rf /tmp/foo.d||rmdir /s /q foo|| || ||# dir-test[#dir-test-note directory test]||if [ -d /tmp ]; then echo directory; fi|| || || ||||||||~ # processes-environment[#processes-environment-note processes and environment]|| ||~ ||~ [#posix posix shell]||~ [#cmd-prompt cmd.exe]||~ [#powershell powershell]|| ||# cmd-line-arg[#cmd-line-arg-note command line args]||$1 _ $2 _ ##gray|//…//## _ _ ##gray|# number of args:## _ $# _ _ ##gray|# pass args as $# words to twiddle## _ twiddle “$@” _ _ ##gray|# pass args as one word to twiddle## _ twiddle “$”||%1 _ %2 _ ##gray|//…//## _ _ ##gray|rem number of args:## _ set #=0 _ for %%i in % do set /a #+=1 _ echo %#% _ _ ##gray|rem no way to pass argument with space## _ twiddle %*|| || ||# program-name[#program-name-note program name]||$0||%0|| || ||# env-var[#env-var-note environment variable] _ ##gray|//get, set, clear//##||##gray|//shell variables are environment variables//## _ $HOME|| ||$env:home|| ||# user-id-name[#user-id-name-note user id and name]||id _ _ ##gray|# user name only; most systems:## _ whoami|| || || ||# exit[#exit-note exit]||exit 0||##gray|rem batch script exits:## _ exit /b 0 _ _ ##gray|rem also closes cmd.exe window:## _ exit 0||exit|| ||# external-cmd[#external-cmd-note external command]||ls||dir||dir|| ||# cmd-subst[#cmd-subst-note command substitution]||s=$(ls)||##gray|//none//##||$s=dir|| ||[#speech speech]||##gray|//mac only://## _ say “I’m a Mac”|| ||$sp = new-object -comobject “SAPI.SpVoice” _ $sp.speak(“I’m a PC”)|| ||[#command-path command path]||which ping|| ||get-command ping|| ||[#set-signal-handler set signal handler]||function int_handler { _ @<  >@echo “exiting…”; _ @<  >@exit _ } _ _ trap int_handler INT|| || || ||# send-signal[#send-signal-note send signal]||kill -INT 1234 _ kill -KILL 1234|| || || ||[#start-background-job start job in background]||sleep 1000 &|| || || ||[#suspend-job suspend current job]||##gray|//^Z//##|| || || ||# terminate-job[#terminate-job-note terminate job]||kill %1|| || || ||[#list-jobs list jobs]||jobs|| || || ||[#background-suspended-job background suspended job]||bg %1|| || || ||[#foreground-background-job bring background job into foreground]||fg %1|| || || ||[#disown-job disown job]||disown %1|| || || ||||||||~ # libraries-namespaces[#libraries-namespaces-note libraries and namespaces]|| ||~ ||~ [#posix posix shell]||~ [#cmd-prompt cmd.exe]||~ [#powershell powershell]|| ||[#library library]||$ cat foo.sh _ function add() { _ @<  >@echo $(($1 + $2)); _ }|| ||##gray|//from directory in search path://## _ _ @@>@@ type Modules\Foo\Foo.psm1 _ function add { _ @<  >@param ($a, $b) _ @<  >@$a + $b _ }|| ||[#import-library import library]||source foo.sh _ add 3 7|| ||import-module foo _ _ add 1 2|| ||[#library-path-env library path environment variable]||##gray|//none//##|| ||$env:psmodulepath|| ||||||||~ # reflection[#reflection-note reflection]|| ||~ ||~ [#posix posix shell]||~ [#cmd-prompt cmd.exe]||~ [#powershell powershell]|| ||# cmd-line-doc[#cmd-line-doc-note command line documentation]||man ls||help dir||get-help get-childitem|| ||[#list-variables list defined variables]||printenv||set||get-variable|| ||[#list-available-lib-note list available libraries]|| || ||get-module -listavailable|| ||||||||~ # debugging-profiling[#debugging-profiling-note debugging and profiling]|| ||# check-syntax[#check-syntax-note check syntax]||$ apt-get install shellcheck _ $ shellcheck foo.sh|| || || ||# stronger-err[#strong-err-note flags for stronger errors]||##gray|//bash only://## _ bash -eu -o pipefail _ _ ##gray|-e: //exit with nonzero status if command fails// _ -u: //exit with nonzero status if undefined variable accessed// _ -o pipefail: //exit with nonzero status if command in pipeline fails//##|| || || ||# cpu-usage[#cpu-usage-note cpu usage]||time ls|| || || ||~ ||~ [#posix posix shell]||~ [#cmd-prompt cmd.exe]||~ [#powershell powershell]|| ||~ ||~ ##EFEFEF|@@_______________________________________________________@@##||~ ##EFEFEF|@@____________________________________________________@@##||~ ##EFEFEF|@@_______________________________________________________@@##||

# general-note + [#general General]

# version-used-note ++ [#version-used version used]

The version of the language used for verifying the examples in the reference sheet.

# version-note ++ [#version show version]

How to get the version.

cmd.exe

The version number displayed at start up is the Windows kernel version. 6.3 is the Windows 8.1 kernel version number.

# grammar-execution-note + [#grammar-execution Grammar and Execution]

# interpreter-note ++ [#interpreter interpreter]

The customary name of the interpreter and how to invoke it.

posix shell:

On Unix, scripts are executing by passing the file containing the script to the interpreter as an argument:

code $ dash ~/configure.sh /code

If the executable bit is set, the file can be run directly:

code $ ~/configure.sh
/code

To determine the name of the interpreter that will process the script, Unix will look for the presence of a shebang (#!) at the start of the file. If the pathname to a command follows the shebang, it will be used to interpret the script. If no shebang is present, the script will be interpreted with {{/bin/sh}} which is {{bash}} on Mac OS X and Cygwin and {{dash}} on Ubuntu.

Command line arguments which set the positional parameters $1, $2, and so on can be set upon invocation as follows:

code $ dash ~/configure.sh arg1 arg2 $ ~/configure.sh arg1 arg2 /code

Arguments can also be put on the shebang line, but this is only useful for passing options to the shell. If the file {{foo.sh}} contains

code #!/bin/sh -x /code

then invoking it as

code ./foo.sh /code

is equivalent to

code /bin/sh -x foo.sh /code

Hardcoding a full path in a shebang is a common cause of portability problems because different systems may install the interpreter in different locations. The {{env}} command avoids the problem by searching the PATH directories for the command:

code #!/usr/bin/env lua /code

powershell:

On Windows, a file is a PowerShell script if it has a {{.ps1}} suffix. There is no need to mark the script as executable. However, PowerShell is not configured to run scripts by default. To change the configuration, start a PowerShell as an Administrator and run the following command:

code set-executionpolicy remotesigned /code

It is possible to invoke a PowerShell script by specifying the PowerShell interpreter as the command and the script as an argument, but the suffix of the file must still be {{ps1}}:

code powershell -file .\test.ps1 /code

# repl-note ++ [#repl repl]

How to invoke the REPL.

# exec-and-exit-note ++ [#exec-and-exit execute command and exit]

How to pass a single command to be executed as a command line argument.

# stmt-separator-note ++ [#stmt-separator statement separator]

How the parser determines the end of a statement.

posix shell:

A posix shell //simple command// consists of optional variable assignments, followed by a command and zero or more arguments and redirections. The command can be an external command, user defined function, or built-in.

A posix shell //pipeline// is a sequence of one or more //simple commands// joined by pipes |. The shell executes the commands in parallel and redirects the stdout of each command to the stdin of the following command. The exit status is the status of the last command.

The //control operators// ; & && || are //pipeline// separators. The semicolon ; enforces sequential execution. The ampersand & executes in parallel. The && executes to the first //pipeline// that returns a nonzero status. The || executes to the first //pipeline// that returns a zero status.

A //list// is one or more //pipelines// joined by //control operators//. A //list// can have a semicolon ; or ampersand & at the end. A //list// is terminated by a newline.

A newline does not terminate a //list// when:

A newline that would normally terminate a statement can be escaped with a backslash.

Multiple lists can be grouped inside parens ( ) or curly brackets { }. When grouped inside parens, the lists are executed inside a subshell. The curly brackets, but not the parens, must be separated from their contents by white space. Also, within curly brackets, but not within parens, the last list must be terminated by a semicolon or newline.

# word-separator-note ++ [#word-separator word separators]

# esc-special-char-note ++ [#esc-special-char escape special character]

How to escape a special character.

# block-delimiters-note ++ [#block-delimiters block delimiters]

How blocks are delimited.

posix shell:

Blocks can be delimited with {}, (), or the //do//,//done// keywords.

If a block is started with an open curly bracket {, then the block must be terminated with a line containing a close curly bracket by itself }.

If a block is delimited by (), then the commands in the block are executed in a subshell.

A block is delimited by //do// and //done// when using the execution control keywords //for//, //select//, //while//, and //until//.

The //then// and //else// keywords of an //if// statement start blocks which are terminated by a following //elif//, //else//, or //fi//.

The //function// and //if// keywords open blocks which are terminated by //end// keywords. The //repeat// keyword opens a block which is terminated by //until//.

# comment-note ++ [#comment to end-of-line comment]

How to make the remainder of the line a comment.

# multiline-comment-note ++ [#multiline-comment multiline comment]

How to comment out multiple lines.

posix shell:

The method described is the syntax for a here document, which is a multiline string literal.

# var-expr-note + [#var-expr Variables and Expressions]

# assignment-note ++ [#assignment assignment]

How to assign a value to a variable.

# parallel-assignment-note ++ [#parallel-assignment parallel assignment]

How to assign values to variables in parallel.

# swap-note ++ [#swap swap]

How to exchange the values held by two variables.

# compound-assignment-note ++ [#compound-assignment compound assignment operators: arithmetic, string, bit]

The compound assignment operators for arithmetic, string, and bit operations

powershell:

Note that {{/=}} performs float division, even when both operands are integers.

When the left operand is a string, {{+=}} concatenates the right operand to the left operand.

When the left operand is a string and the right operand an integer, {{*=}} concatenates the left operand with itself //right operand// times.

# incr-decr-note ++ [#incr-decr increment and decrement]

The C-style increment and decrement operators which can be used in expressions.

# var-decl-note ++ [#var-decl variable declaration]

How to declare a variable.

posix shell:

The following three lines have identical behavior:

code A="hello, world” declare A="hello, world” typeset A="hello, world” /code

It is possible to make a read only variable. Again there are three ways:

code readonly A="can’t change” declare -r A="can’t change” typeset -r A="can’t change” /code

Variables are not exported to subprocesses unless declared to be exported:

code export A="exported to subprocess” declare -x A="exported to subprocess” typeset -x A="exported to subprocess” /code

Variables assigned on the same line as a command are not created, only exported to the subprocess that instantiates the command:

code EDITOR=emacs svn commit /code

By default variables defined inside functions are global. They can be declared to be local:

code function foo () { local b=17 # echoes 17: echo $b }

echoes nothing:

echo $b /code

# identifiers-case-sensitive-note ++ [#identifiers-case-sensitive are identifiers case sensitive?]

powershell:

PowerShell identifiers are case insensitive.

# null-note ++ [#null null]

The null literal.

# null-test-note ++ [#null-test null test]

How to test if a value is null.

# arithmetic-logic-note + [#arithmetic-logic Arithmetic and Logic]

posix shell:

The POSIX shell provides at least three different environments for logical expressions, each with their own operators and values for true and false.

Logical expressions are usually encountered in the conditionals of {{if}}, {{elif}}, {{while}}, and {{until}}. A command is expected as the conditional expression. The command is executed, and a return value of zero is treated as true and nonzero as false.

||~ ||~ status codes||~ [ ]||~ $(( ))|| ||where used||command||command||argument|| ||true||true||##gray|//no canonical true value//##||1|| ||false||false||’’||0|| ||falsehoods||##gray|//nonzero exit status//##||’’||0|| ||logical operators||&& @@||@@ !||-a -o !||&& @@||@@ !|| ||grouping||{ }||( )||( )|| ||string relational operators||##gray|//none//##|| = != < >||##gray|//none//##|| ||arithmetic relational operators||##gray|//none//##||-eq -ne -lt -gt -le -ge||== != < > <= >=|| ||arithmetic operators||##gray|//none//##||##gray|//none//##||+ - * / % **|| ||bit operators||##gray|//none//##||##gray|//none//##||@@ << @@ @@ >> @@ & | ^ ~||

posix shell: status codes:

Logical expressions can be formed using status codes returned by commands. The commands can be external, built-in, or user defined functions. A status code of zero is used to indicate success, and for the purpose of logic zero is treated as true and all other status codes as false.

The && and @@||@@ operators are short circuit operators. An exclamation point ! can be used to negate the status code of a command. It is not necessary to separate && and @@||@@ from their operands with whitespace, but it is necessary to mark off a ! used as negation with whitespace.

posix shell: test command:

posix shell: arithmetic expansion:

# true-false-note ++ [#true-false true and false]

The literals for true and false.

# falsehoods-note ++ [#falsehoods falsehoods]

Values which are false in conditional expressions.

# logical-ops-note ++ [#logical-ops logical operators]

Logical and, or, and not.

posix shell:

&& || and ! are available inside , (( )), and $(( )) expressions. Inside [ ] expressions use -a, -o, and !.

# conditional-expr-note ++ [#conditional-expr conditional expression]

The syntax for a conditional expression.

# expression-statement ++ are expressions statements

Whether an expression can be used where a statement is expected.

# relational-expr ++ relational expressions

posix shell:

Bash has three types of relational expressions: , [ ], and (( )). For a description of [ ], read the [http://www.google.com/search?q=man+test man page for test].

(( )) evaluates its contents in the same manner as the arithmetic expansion $(( )). If the result is zero, it returns 1 (false). Otherwise it returns 0 (true).

//pattern//## and //pattern//## interpret * and ? on the right side as patterns. Thus “hello” == “hell*” is true. For numeric comparison, use [ $a -eq ##gray|//num//## ] or [ $a -ne ##gray|//num//## ].

[#bash-expressions Bash expressions] discusses the different types of bash expressions in more detail.

# relational-operators ++ relational operators

posix shell:

If == and =! have an unquoted string on the right, then * and ? within the string will be treated as wild cards for matching.

# string-to-number ++ convert from string

posix shell:

All values are strings. The $(( )) operator will interpolate any variables and then evaluate the resulting string as an arithmetic expression composed of integers. The variables are not limited to containing integers. The following script outputs 10:

code A=7+3 echo $(($A)) /code

To perform floating point arithmetic, bash must shell out to a floating point utility such as //bc//.

# number-to-string ++ convert to string

# arithmetic-expr ++ arithmetic expressions

How to evaluate an arithmetic expression.

posix shell:

Bash arithmetic is available within $(( )) and (( )). The latter form evaluates the arithmetic expression and returns status 1 if the result zero, and 0 otherwise.

Bash only has integer arithmetic. For floating point arithmetic, use the external commands //bc// or //dc//.

# arithmetic-operators ++ arithmetic operators

The operators for addition, subtraction, multiplication, float division, integer division, modulus, and exponentiation. Some languages provide a function //pow// instead of an operator for exponentiation.

posix shell:

arithmetic operators are available in $(( )) and (( )).

# integer-division ++ integer division

How to perform integer division.

# float-division ++ float division

How to perform floating point division, even if the operands might be integers.

posix shell:

The bash shell lacks built-in floating point arithmetic. //bc// is an arbitrary precision calculator, and //scale// is the number of digits to the right of the decimal point. If scale is not specified, it defaults to zero, which results in integer division.

It is also possible to use //dc//, which is a reverse polish notation arbitrary precision calculator:

code echo " 5 k $a $b / p " | dc /code

# arithmetic-functions ++ arithmetic functions

Functions for computing square root, natural exponent, natural logarithm, sine, cosine, tangent, arcsine, arccosine, arctangent, and //atan2//.

The trigonometric functions are all in radians. //atan2// takes two arguments which are the x and y co-ordinates of a vector in the Cartesian plane. It returns the angle to the positive x-axis made by the vector.

# arithmetic-truncation ++ arithmetic truncation

# division-zero ++ division by zero

# integer-overflow ++ integer overflow

# float-overflow ++ float overflow

# sqrt-negative-two ++ sqrt -2

The result of taking the square root of -2.

# random ++ random integer, uniform float

The examples show how to generate a uniform random integer in the range from 0 to 99, inclusive; how to generate a uniform float in the range 0.0 to 1.0; how to generate a float from a standard normal distribution

posix shell:

$RANDOM evaluates to a random integer between 0 and 32767 inclusive.

# seed-random ++ seed random numbers

posix shell:

Bash 3.2.48 seeds the random number at start up using the current time and the PID:

code /* Seed the random number generator. */ sbrand (dollardollarpid + shellstarttime); /code

Here is the random number generation code:

code /* A linear congruential random number generator based on the example one in the ANSI C standard. This one isn’t very good, but a more complicated one is overkill. */

/* Returns a pseudo-random number between 0 and 32767. */ static int brand () { rseed = rseed * 1103515245 + 12345; return ((unsigned int)((rseed >> 16) & 32767)); /* was % 32768 */ } /code

powershell:

The initial seed is set to a value that varies each time PowerShell is started up.

If a repeatable sequence of random numbers is desired, the seed can be set to a specific value using the {{-setseed}} option on the first call to {{random}}.

# bit-operators ++ bit operators

posix shell:

The bit operators are available in $(( )) and (( )).

# strings-note + [#strings Strings]

# string-literal ++ string literal

The syntax for a string literal and how to escape the delimiter.

# string-literal-newline ++ newline in literal

Whether a newline character sequence can be included in a string.

For all the languages described in this reference sheet a string literal is permitted to encompass multiple lines in the source code and the resulting string will contain the same number of lines.

# string-escapes ++ escapes

Character escape sequences which can be used in string literals.

# variable-interpolation ++ variable interpolation

How to interpolate variables in a string.

posix shell:

A dollar sign {{$}} can be backslash escaped to prevent variable interpolation:

code echo “the value of $a is $a” /code

powershell:

A dollar sign {{$}} can be backtick escaped to prevent variable interpolation:

code write-output “the value of @@`@@$a is $a” /code

# string-length ++ length

How to get the length of a string.

cmd.exe:

code :strLen string len – returns the length of a string :: – string [in] - variable name containing the string being measured for length :: – len [out] - variable to be used to return the string length ( SETLOCAL ENABLEDELAYEDEXPANSION set “str=A!%~1!”& set “len=0” for /L %%A in (12,-1,0) do ( set /a “len|=1<<%%A” for %%B in (!len!) do if “!str:~%%B,1!”==”” set /a “len&=~1<<%%A” ) ) ( ENDLOCAL IF “%~2” NEQ ““ SET /a %~2=%len% ) EXIT /b /code

# string-comparison ++ string comparison

How to determine if two strings are equal or unequal.

# index-substring ++ index substring

How to find the index of the start of a substring in a string.

# extract-substring ++ extract substring

# string-concatenation ++ string concatenation

The string concatenation operator.

# split ++ split

How to split a string into an array of strings.

powershell:

When splitting a string into words, no delimiter need be specified and the string to be split can follow the {{-split}} operator:

code -split “foo bar baz” /code

# join ++ join

How to concatenate the elements of an array into a string with a separator.

# scan ++ scan

# sprintf ++ sprintf

How to create a string using a printf style format.

# case ++ case manipulation

# strip ++ strip

# pad ++ pad on right, pad on left

# regex-note + [#regexes Regular Expressions]

# regex-match-note ++ [#regex-match regex match]

How to test whether a regular expression matches a string.

posix shell:

The double square bracket operator {{ }} is not part of the POSIX standard but it is a feature of {{bash}}, {{ksh}}, and {{zsh}}. It supports a match test operator:

code if [[ “hello” =~ ^[a-z][a-z]*$ ]]; then /code

# single-subst-note ++ [#single-subst single substitution]

How to replace the first occurrence of a pattern in a string.

posix shell:

The following parameter expansion is not part of the POSIX standard but provided by {{bash}}, {{ksh}}, and {{zsh}}:

code str=’do re mi mi mi’ echo ${str/mi/ma} /code

# global-subst-note ++ [#global-subst global substitution]

How to replace all occurrences of a pattern in a string.

posix shell:

The following parameter expansion is not part of the POSIX standard but provided by {{bash}}, {{ksh}}, and {{zsh}}:

code str=’do re mi mi mi’ echo ${str//mi/ma} /code

# dates-time-note + [#dates-time Dates and Time]

# arrays-note + [#arrays Arrays]

# array-literal ++ array literal

Array literal syntax.

# array-size ++ array size

How to get the number of elements in an array.

# array-lookup ++ array lookup

How to access a value in an array by index.

# array-slice ++ array slice

How to slice a subarray from an array.

# array-iteration ++ array iteration

# membership ++ membership

How to test for membership in an array.

# intersection ++ intersection

How to compute an intersection.

# union ++ union

# map ++ map

# filter ++ filter

# reduce ++ reduce

# universal-predicate ++ universal predicate

How to test whether a condition holds for all members of an array. Always true for an empty array.

# existential-predicate ++ existential predicate

How to test whether an item in an array exists for which a condition holds. Always false for an empty array.

# dictionary-literal ++ dictionary literal

# dictionary-size ++ dictionary size

# dictionary-lookup ++ dictionary lookup

# dictionary-iteration ++ dictionary iteration

# out-of-bounds ++ out of bounds behavior

# functions-note + [#functions Functions]

Python has both functions and methods. Ruby only has methods: functions defined at the top level are in fact methods on a special main object. Perl subroutines can be invoked with a function syntax or a method syntax.

# function-definition ++ function definition

posix shell:

A bash function definition can alternately be preceded by the keyword //function//, and when used, the parens following the function name are prohibited.

# function-invocation ++ function invocation

posix shell:

The syntax for invoking a function is the same as the syntax for invoking a command. If a function is defined with the same name as a command in the search path, the function will be executed.

# missing-argument ++ missing argument value

Value of an argument variable if a function is invoked with fewer arguments than are declared.

# extra-arguments ++ extra arguments

If a function is invoked with more arguments than are declared, how the function can access them.

# default-argument ++ default argument value

How to declare a default value for an argument.

# variable-arguments ++ variable number of arguments

How to write a function which accepts a variable number of argument.

# named-parameters ++ named parameters

How to write a function which uses named parameters.

# return-value ++ return value

posix shell:

Bash functions can only return small integers via return. However, a function can echo to stdout and the caller can invoke it with backticks to get a string value.

# lambda-declaration ++ lambda declaration

How to define a lambda function.

# lambda-invocation ++ lambda invocation

# default-scope ++ default scope

posix shell:

By default, bash and variables inside functions have global scope.

# execution-control-note + [#execution-control Execution Control]

# if ++ if

Some optional branching constructs:

posix shell:

code case $a in (0) echo “no”;; (1) echo “yes”;; (2) echo “maybe”;; (*) echo “error”;; esac /code

# while ++ while

posix shell:

Also has an //until// loop.

# break-continue ++ break/continue/redo

//break// exits a //for// or //while// loop immediately. //continue// goes to the next iteration of the loop. //redo// goes back to the beginning of the current iteration.

# for ++ for

posix shell:

A C-style for loop:

code for ((i=0; i<10; i++ )); do echo $i; done /code

# exceptions-note + [#exceptions Exceptions]

# raise-exception ++ raise exception

How to raise an exception.

# catch-exception ++ catch exception

How to handle an exception.

# uncaught-exception ++ uncaught exception behavior

System behavior if an exception goes uncaught. Most interpreters print the exception message to stderr and exit with a nonzero status.

posix shell:

The bash interpreter writes a message to stderr whenever a command returns a nonzero status. By default, the interpreter does not exit, but if this behavior is desired, then the following should be put at the top of the script:

code trap exit ERR /code

# wait-on-thread ++ wait on thread

# streams-note + [#streams Streams]

# print-to-stdout ++ write to standard out

posix shell:

To prevent //echo// from appending a newline to the output, use

code echo -n “hello” /code

# standard-filehandles ++ standard filehandles

# read-line ++ read line

# read-file ++ read file

# write-file ++ write to file

# append-file ++ append to file

# files-note + [#files Files]

# directories-note + [#directories Directories]

# processes-environment-note + [#processes-environment Processes and Environment]

# external-command ++ external command

posix shell:

The syntax for calling an external command is the same as the syntax for invoking a function. If a function is defined with the same name as an external command in the search path, the function is invoked.

# backticks ++ backticks

# command-line-args ++ command line args

# speech ++ speech

How to make the computer talk.

posix shell:

On Mac OSX the command {{say}} can also be executed from the bash or zsh prompt:

code say “I’m a Mac” /code

On Ubuntu Linux this command can be used:

code espeak “I’m Unix” /code

# environment-variable ++ environment variable

# command-path ++ command path

The directory containing a command. Also indicates if the command is a built-in, alias, or function. Shows the definition of aliases and functions.

# exit ++ exit

posix shell:

The exit status of a bash script is the return status of the last command executed, or the argument of //exit//.

# set-signal-handler ++ set signal handler

# libraries-namespaces-note + [#libraries-namespaces Libraries and Namespaces]

# library ++ library

What a library looks like.

# import-library ++ import library

# library-path ++ library path

# namespace-declaration ++ namespace declaration

# namespace-separator ++ namespace separator

# reflection-note + [#reflection Reflection]

# class ++ class

# debugging-profiling-note + [#debugging-profiling Debugging and Profiling]

# posix + [#top POSIX Shell]

[http://pubs.opengroup.org/onlinepubs/9699919799/idx/xcu.html POSIX 2008: Shell & Utilities]

# cmd-prompt + [#top Command Prompt]

[http://technet.microsoft.com/en-us/library/bb490890.aspx Command-line reference A-Z]

# powershell + [#top PowerShell]

[http://technet.microsoft.com/en-us/library/cc196356.aspx Windows PowerShell User’s Guide]