Module oursh::program::posix [−][src]
Expand description
The shell language (often called sh
) at the heart of the most popular
shells.
While shells typically implement many extensions to the POSIX standard
we’ll be implementing only the most basic set of functionality and
offloading all extensions to the modern
language.
Compatibility
Shell languages like bash
or zsh
are supersets of the POSIX sh
language. This means two things:
- All
sh
programs are validbash
,zsh
, etc programs - Not all
bash
programs, for example, are validsh
programs.
This explains why some shell scripts will start with #!/bin/sh
or
#!/bin/bash
, depending on what features of the language the script needs.
Examples
There are more than enough examples of sh
scripts out there, but here is
a collection of examples tested in this shell’s implementation of the
POSIX standard. This section will not be a complete description of the
syntax of the sh
language, but will be updated with as many interesting
cases as possible.
Running a command (like date
) in a shell script is the simplest thing
you can do.
date date --iso-8601 ./a.out
All variables start with a $
when referring to them, but when assigning
you omit the $
. It’s also worth mentioning that the lack of whitespace
around the =
in assignment is required. It’s often conventional to
write your variable names in all caps, but this is not a limitation of the
language.
NAME="Nathan Lilienthal" i=0 echo $NAME echo $i
Variables are loaded from the environment (often simply called ENV
) as
well. For more information on the enviroment read
section 8.1.
echo $PATH echo $TERM
In addition to variables beginning with a $
being expanded to the value
they were set to, other syntax can perform expansion. See section 3§2.6 for
a complete description of word expansion.
echo ${1} echo ${1:-default} echo ${1:=default} echo ${1:?} echo ${1:+new} echo ${#1} echo ${1%.*} echo ${1%%.*} echo ${1#prefix_}
In addition to running a program at the top level, programs can be run in a subshell with mechanisms to capture the output. This is called command substitution.
files=`ls` files=$(ls) # Same as above.
Conditionals in the wild are often written with the non-POSIX [[
syntax,
traditional conditional checks use either test
or [
.
if test -z "$1"; then exit 1 fi if [ "$1" -eq "foo" ]; then echo "bar" fi
Specification
The syntax and semantics of this module are strictly defined by the POSIX (IEEE Std 1003.1) standard, in section 3§2 of “The Open Group Base Specifications” [1].