Bash Command Substitution – Can Command Substitution Be Nested in Variable Substitution?

bashcommand-substitutionvariable substitution

I would like to use variable substitution on a particular string that I access via a command. For example, if I copy something into my clipboard, I can access it like this.

$ xclip -o -selection clipboard
Here's a string I just copied.

If I assign it to a variable, then I can do variable substitution on it.

$ var=$(xclip -o -selection clipboard)
$ echo $var
Here's a string I just copied.
$ echo ${var/copi/knott}
Here's a string I just knotted.

However, is there a way to do variable substitution without assigning it to a variable? Conceptually, something like this.

$ echo ${$(xclip -o -selection clipboard)/copi/knott}
bash: ${$(xclip -o -selection clipboard)/copi/knott}: bad substitution

This syntax fails, because var should be a variable name, not a string.

Best Answer

No, you can't. bash and most other shells (except zsh) don't allow nested substitution.

With zsh, you can do nested substitution:

$ echo ${$(echo 123)/123/456}   
456
Related Question