0

I am trying to do string substitution in bash, want to understand it better.

I crafted a success case like this:

a=abc_de_f
var=$a
echo ${var//_/-}

outout is abc-de-f. This works.

However, the following script fails:

a=abc_de_f
echo ${$a//_/-}

The error message is ${$a//_/-}: bad substitution. It seems like related to how we can use a variable in substitution. Why this fails? How bash handles variables in this case?

Also, what is the best practice to handle escape characters in bash string substitution?

1 Answer 1

6

In the second case, you don't need the second $ as a is the string.

a=abc_de_f
echo ${a//_/-}

If you wanted to add a level of indirection, you can use ! before the variable as in

a=abc_de_f
b=a
echo ${b//_/-}

will output a, while

echo ${!b//_/-}

will output abc-de-f.

See here for a discussion on the art of escaping in BASH

Sign up to request clarification or add additional context in comments.

1 Comment

Upvoted for linking to wiki.bash-hackers.org, where I found the solution to my problem. Thank you!!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.