@oguz ismail 2019-10-08 10:59:44

+(...) is extended glob syntax, you need to enable extglob feature for bash to understand it. And as stated in the other answer, normally a circumflex shouldn't be used for negating a character class. Bash tolerates this mistake, but anyways let's use the correct syntax for the sake of portability:

shopt -s extglob
echo "${p%%+([!/])}"
echo "${p#${p%%+([!/])}}"



Related link: Bash Reference Manual § Pattern Matching.

And btw, you don't really need extended globs for this.

echo "${p%${p##*/}}"
echo "${p##*/}"

Above script works just as well on any POSIX-compliant shell.

@mirabilos 2019-10-09 13:57:09

Another, more standards-compliant, Korn shell actually outputs


followed by an empty line. This is because shell globs are not regular expressions, and the character class negotiation operator is a false friend.

In POSIX shell, [^/] is actually unspecified but normally (["^"/] is more clear) means “either ^ or /” but you will want “anything that’s not /” which, in POSIX shell globs, is [!/] instead.

See the other answer for an explanation on how GNU bash needs shopt -s extglob to support Korn shell-compatible extended globbing patterns in addition.

Related Questions

Sponsored Content

Sponsored Content