Is "${blah}"
allowed in POSIX sh, or does this require bash derived shells?
2 Answers
"${blah}"
and "$blah"
are portable shell syntax: they work on all POSIX-compliant shells as well as in traditional Bourne shells. POSIX also requires other features of variable expansion:
- String manipulation with
${VAR#PREFIX}
,${VAR##PREFIX}
,${VAR%SUFFIX}
and${VAR%%SUFFIX}
. - Conditional treatment of unset variables with
${VAR-DEFAULT}
,${VAR=DEFAULT}
,${VAR+FALLBACK}
and${VAR?MESSAGE}
as well as the unset-or-empty variants with:-
,:=
,:+
and:?
. - Variable length with
${#VAR}
.
In all cases, remember that the result of $…
undergoes whitespace-splitting (more precisely, splitting at $IFS
characters) and wildcard expansion (globbing) unless it's in double quotes (or a few other contexts that don't allow multiple words).
You can look up what exists in POSIX by reading the specification. Modern versions of POSIX are identical to the Open Group Base Specifications (without optional components). Older versions are a subset of Single Unix v2.
Unix-like systems without a POSIX shell are extremely rare nowadays. /bin/sh
is a non-POSIX Bourne shell on a few systems, notably Solaris, but a POSIX shell is available (/usr/xpg4/bin/sh
on Solaris, and you should have /usr/xpg4/bin
ahead of /usr/bin
in your PATH). If you need compatibility with Bourne shells, check the man page on the systems you're interested in, as there have been many versions of sh with slightly different sets of features. Sven Mascheck maintains a page with a lot of information.
-
3
-
1Also,
$var
and${var}
are identical (unless expanded as part of a double-quoted string with an immediately following character that is a valid character in variable names). Some users seem to think${var}
automatically "quotes" the expansion. It does not.– Kusalananda ♦Commented May 19, 2018 at 8:28 -
Link to latest version (v. 2018 as of year 2024): pubs.opengroup.org/onlinepubs/9699919799.2018edition/utilities/…– Jack GCommented Jan 29 at 9:40
In the POSIX spec the section on Parameter Expansion says...
The format for parameter expansion is as follows:
${expression}
where expression consists of all characters until the matching '}'.
snip
The simplest form for parameter expansion is:
${parameter}
Then in the section on double-quoting...
Enclosing characters in double-quotes ( "" ) shall preserve the literal value of all characters within the double-quotes, with the exception of the characters backquote, , and , as follows:
$ The dollar-sign shall retain its special meaning introducing parameter expansion (see Parameter Expansion), a form of command substitution (see Command Substitution), and arithmetic expansion (see Arithmetic Expansion).
So, yes.