Getting started with sh
Remarks#
sh
is not a single shell. Rather, it is a specification with the POSIX operating system standard for how a shell should work. A script that targets this specification can be executed by any POSIX-compliant shell, such as
bash
ksh
ash
and its derivatives, such asdash
zsh
In a POSIX-compliant operating system, the path /bin/sh
refers to a POSIX-compliant shell. This is usually a shell that has features not found in the POSIX standard, but when run as sh
, will restrict itself to the POSIX-compliant subset of its features.
References
- Standard
sh
- The FreeBSD
sh(1)
man-page - The NetBSD
sh(1)
man-page - The OpenBSD
sh(1)
man-page - The Illumos
sh(1)
man-page (ksh93(1)
)
Hello, world!
With echo
:
$ echo Hello, world!
Hello, world!
With printf
:
$ printf 'Hello, world!\n'
Hello, world!
As a file:
#!/bin/sh
printf '%s\n' 'Hello, world!'
Echo Portability
$ for shell in ash bash dash ksh ksh93 zsh; do
> $shell -c "echo '\\\\'$shell'\\\\'"
> done
\\ash\\
\\bash\\
\dash\
\pdksh\
\\ksh93\\
\zsh\
‘echo’ can only be used consistently, across implementations, if its arguments do not contain any backslashes (reverse-solidi), and if the first argument does not start with a dash (hyphen-minus). Many implementations allow additional options, such as -e
, even though the only option allowed is -n
(see below).
From POSIX:
If the first operand is -n, or if any of the operands contain a
character, the results are implementation-defined.