3

How can I inline a command substitution in a bash parameter expansion instead of having to save the command substitution as a variable and then using that variable in the parameter expansion?

# inlined fails in bash; this works, however, in zsh
echo ${"$(ps -p $$)"##*[[:cntrl:][:punct:][:space:]]}

# separate variable works (in both bash & zsh)
p="$(ps -p $$)"
echo ${p##*[[:cntrl:][:punct:][:space:]]}
XDR
  • 4,070
  • 3
  • 30
  • 54
  • 4
    You can't (short of using `eval`, which you should *not* do) in `bash`. – chepner Mar 17 '20 at 13:29
  • 1
    You would need to use a pipe like `ps -p "$$" | sed 's/.*[[:cntrl:][:punct:][:space:]]//'` – chepner Mar 17 '20 at 13:33
  • 1
    `echo $(v=$(ps -p $$); echo "${v##*[[:cntrl:][:punct:][:space:]]}")` – KamilCuk Mar 17 '20 at 13:55
  • 2
    Z-shell is amazing at allowing nested substitutions. Unlike bash, it allows `${${…}}` (my understanding is that `${…}` operates on a string rather than a variable, thus it also allows `${$(…))`). Bash is an improved clone of [bsh](https://en.wikipedia.org/wiki/Bourne_shell) while zsh an improved [ksh](https://en.wikipedia.org/wiki/KornShell), which is an improved clone of bsh. They have a lot of feature parity (each imports ideas from the other) though with subtle differences (like arrays being 0-indexed vs 1-indexed), but in my experience, zsh generally has more functionality. – Adam Katz Mar 17 '20 at 15:48
  • Thanks for the info, everyone. Seems like using a variable is the simplest solution, then. – XDR Mar 17 '20 at 16:42

0 Answers0