What kinds of string interpolation does POSIX sh support?

6,628

Solution 1

"${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.

Solution 2

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.

Share:
6,628

Related videos on Youtube

mcandre
Author by

mcandre

Updated on September 18, 2022

Comments

  • mcandre
    mcandre almost 2 years

    Is "${blah}" allowed in POSIX sh, or does this require bash derived shells?

  • user541686
    user541686 about 6 years
    Where has your answer been all my life! +1
  • Kusalananda
    Kusalananda about 6 years
    Also, $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.