1

I my bash script, I have a string variable with a $ sign it, and the it isn't escaped. It looks like this:

x="hello $world"

Obviously, when I echo "$x", the output is hello, since $world is being interpreted as a variable. My goal is to modify the string to be hello \$world. I tried several techniques, listed below. None of them seem to be working:

y="$(echo "$x" | sed 's/\$/z/g')" (outputs hello)

y="$(echo "$x" | sed 's/$/z/g')" (outputs hello z, even though I didn't escape \ in sed)

Even tried Bash's native string replacement through:

y=${x//\$/z} (outputs hello)

I realize that I could easily do any of these if the string weren't stored in a variable, but the way my script works, this string will be stored in a variable first, so I need to figure out how to add the \ after that. I don't care if I create a new copy of the string or edit the same string.

5
  • In your second sed command, the $ (quoted from bash) matches end-of-line, as sed works with basic regular expressions. Commented Dec 21, 2017 at 16:33
  • 1
    How do you store the string in a variable? I you do it like you show it, $world is gone and you can't get it back, as shown in Toby's answer. Commented Dec 21, 2017 at 16:38
  • Contrast your (first) sed command with a single-quoted '$x' like this: y="$(echo '$x' | sed 's/\$/z/g')". This version sets $y to zx. Commented Dec 21, 2017 at 16:49
  • @BenjaminW. I am using a command (jq to be specific) that returns a string that has several unescaped $ signs in it. Commented Dec 21, 2017 at 16:56
  • If you have a string str containing an unescaped $, like hello $world (and it shows up exactly like that when you issue declare -p str), doing echo "$str" will not try to expand the variable name. Can you show your actual assignment? Commented Dec 21, 2017 at 17:10

2 Answers 2

4

The assignment (with $world empty or undefined) is the same as writing

x="hello "

Nothing you do to $x will see a $ in there, unless you add it from outside.

Perhaps you meant instead:

x='hello $world'
Sign up to request clarification or add additional context in comments.

Comments

3

You can use BASH:

x='hello $world'
echo "${x//\$/\\$}"

hello \$world

2 Comments

The question has x="hello $world", not x='hello $world' (hence the problem - there's no $ in $x).
As you already know double quotes will cause variable expansion so we need to use single quote.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.