4

In Linux /etc/init.d/functions script I found the following parameter expansions that I don't quite understand:

${p//[0-9]/}  replace all instances of any number to/by what?

${1##[-+]}  This seems to remove all the longest left instances of minuses and pluses?

${LSB:-}  This seems to say that if LSB is not set then set nothing? in other words do nothing?
Hadi
  • 5,328
  • 11
  • 46
  • 67
  • Tangentially related: The _source and purpose of the `$LSB` variable_ in the context of `/etc/init.d/functions` specifically (such as found on RHEL-like systems), is the subject of [this Unix & Linux SE question](https://unix.stackexchange.com/q/364021/54804). – mklement0 May 16 '17 at 16:19

2 Answers2

4

These are instances of bash Shell Parameter Expansion; see http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html

Note: ksh and zsh support the expansions in your question, too (I'm unclear on the full extent of the overlap in functionality), whereas sh (POSIX-features-only shells), does NOT support the string-replacement expansion, ${p//[0-9]/}.


${p//[0-9]/}

Removes all digits: replaces all (//) instances of digits ([0-9]) with an empty string - i.e., it removes all digits (what comes after the last / is the replacement string, which is empty in this case).

${1##[-+]}

Strips a single leading - or +, if present: Technically, this removes the longest prefix (##) composed of a single - or + character from parameter $1. Given that the search pattern matches just a single character, there is no need to use ## for the longest prefix here, and # - for the shortest prefix - would do.

${LSB:-} 

A no-op designed to prevent the script from breaking when run with the -u (nounset) shell attribute: Technically, this expansion means: In case variable $LSB is either not set or empty, it is to be replaced with the string following :-, which, in this case, is also empty.

While this may seem pointless at first glance, it has its purpose, as Sigi points out:

"
The ${LSB:-} construct makes perfect sense if the shell is invoked with the -u option (or set -u is used), and the variable $LSB might actually be unset. You then avoid the shell bailing out if you reference $LSB as ${LSB:-} instead. Since it's good practice to use set -u in complex scripts, this move comes in handy quite often.
"

Community
  • 1
  • 1
mklement0
  • 382,024
  • 64
  • 607
  • 775
  • 1
    +1, *especially* for understanding and explaining what `${1##[-+]}` does since many people get this wrong and use this construct to e.g. strip all leading whitespace or zeroes which **does not work this way**. – Adrian Frühwirth Apr 29 '14 at 08:08
0
${p//[0-9]/} # removes digits from anywhere in `$p`

${1##[-+]} # removes + or - from start in $1

${LSB:-} # not really doing anything
anubhava
  • 761,203
  • 64
  • 569
  • 643