0

So I know that this has been asked a million times on StackExchange, but I am not able to implement the solutions in the other threads in my bash script. Probably I'm just too stupid to understand the answers, so please go easy on me.

For simplicity, the following code is equivalent with what I want to do:

for i in {1..5}
do
    echo $2.svg | grep 'rect x="$i"' && do_something_if_$i_is_found
done

The issue here is that when I wrap $i in double quotes "$i" is treated like a string.

  1. I cannot use single quotes instead because I am looking for x="5" in $2.svg
  2. Escaping the double quotes inside of the single quotes make them a part of the string, i.e. 'rect x=\"$i\"'
L M
  • 13
  • To expand the value of a variable within a quoted string -> use double quotes. To put literal double-quotes in a double-quoted string -> escape them with backslashes. – ilkkachu Dec 29 '22 at 19:54
  • @ilkkachu, thank you, this explains a lot of my issues with bash!! – L M Dec 29 '22 at 20:35

1 Answers1

0

You need to change the quotes:

for i in {1..5}
do
    echo "${2}.svg" | grep 'rect x = '$'\042'$i$'\042' && do_something_if_${i}_is_found
done

\042 is the ASCII representation of double quotes.

Check man ascii

Or simply:

grep "rect x=\"$i\""
  • 1
    I don't think grep can be expected to support octal escapes. The simple fix is to backslash-escape any literal double quotes; "rect x=\"$i\"" – tripleee Dec 29 '22 at 18:34
  • Post edited, tested, works – Gilles Quénot Dec 29 '22 at 18:40
  • or $'rect x = \042'"$i"$'\042', since there's not much need to have the '...' and $'...' separate, but you may want to double-quote the expansion. Though you can just put literal double quotes inside a single-quoted string, so 'rect x = "'"$i"'"' would also do (not that I'm sure it's much clearer) – ilkkachu Dec 29 '22 at 20:03
  • This worked, thank you! It works when wrapping everything in double quotes, like you did in your answer, but not when wrapping everything in single quotes. TIL single and double quotes are not equivalent. – L M Dec 29 '22 at 20:26