0

I have a line in a script that works in zsh but does not work in bash:

SHORTDIR=${${${PWD##*/}//./_dot_}//:/_colon_}

This is basically a short/efficient version of basename $PWD | sed -e 's/\./0/g' -e 's/:/1/g'.

What's the syntax for stringing together variable expansions?

artless noise
  • 21,212
  • 6
  • 68
  • 105
Steven Lu
  • 41,389
  • 58
  • 210
  • 364
  • possible duplicate of [Bash bad substitution with subshell and substring](http://stackoverflow.com/questions/5917439/bash-bad-substitution-with-subshell-and-substring) – perreal Apr 29 '13 at 00:03

3 Answers3

1

I was hoping that there'd be a better way than

SHORTDIR=${PWD##*/}
SHORTDIR=${SHORTDIR//./_dot_}
SHORTDIR=${SHORTDIR//:/_colon_}

but this is what I'm sticking to.

According to the answers to the question linked by @perreal, bash basically does not allow for expanded variables themselves as a "parameter" and that's why it fails.

Steven Lu
  • 41,389
  • 58
  • 210
  • 364
1

Sadly, the first part of the substitution has to be a parameter name. An alternative sed version would be:

echo $PWD | sed -e 's!.*/!!' -e 'y/.:/01/'
perreal
  • 94,503
  • 21
  • 155
  • 181
0

Just to throw this out there, many people don't know that multiple assignments can be done in one line. E.g.:

$ a=1234 a=${a:0:3} a=${a/1}

or

SHORTDIR=${PWD##*/} SHORTDIR=${SHORTDIR//./_dot_} SHORTDIR=${SHORTDIR//:/_colon_}
Larry
  • 310
  • 2
  • 11
  • Useful to know. Does `a=${a/1}` remove the `1` character? I was under the impression that a trailing slash is needed, per [doc](https://www.tldp.org/LDP/abs/html/parameter-substitution.html) – Steven Lu Aug 19 '19 at 15:53
  • 1
    @StevenLu - yes, exactly. The trailing slash isn't needed as the ‘1’ is being replaced with nothing. The doc doesn't mention that; however the bash(1) man page says `If string is null, matches of pattern are deleted and the / following pattern may be omitted.` – Larry Sep 07 '19 at 22:07