0

Fellow StackOverflow,

How should I handle escaping special characters in a string like this:

^VfAro@khm=Y)@5,^AyxPO[[$2jW#+Vg;Paj2ycIj8VUr5z1,}qR~JnK7r_0@$ov

I am using this string in a variable which is piped to cryptsetup luksOpen inside the Bash script:

echo "${string}" | cryptsetup luksOpen UUID={...}

But when executing the script, I got some characters stripped. When echoing the plain string, all the characters are preserved.

I have tried with different variable enclosing as well as with printf "%q" but without any viable result.

Alan Kis
  • 1,790
  • 4
  • 24
  • 47
  • I suspect you're using `string="^VfAro@khm=Y)@5,^AyxPO[[$2jW#+Vg;Paj2ycIj8VUr5z1,}qR~JnK7r_0@$ov"`. If so, you may using single quote instead of double quote as `string='^VfAro@khm=Y)@5,^AyxPO[[$2jW#+Vg;Paj2ycIj8VUr5z1,}qR~JnK7r_0@$ov'` – dibery Aug 30 '19 at 14:04
  • 1
    `printf '%s\n'`. Only use `%q` when generating code that's intended to be `eval`-safe. – Charles Duffy Aug 30 '19 at 14:48
  • related https://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash – Sam Daniel Aug 30 '19 at 14:53

1 Answers1

3

If you do want a trailing newline on the input to cryptsetup:

s='^VfAro@khm=Y)@5,^AyxPO[[$2jW#+Vg;Paj2ycIj8VUr5z1,}qR~JnK7r_0@$ov'
printf '%s\n' "$s" | cryptsetup luksOpen

If you don't want a trailing newline:

s='^VfAro@khm=Y)@5,^AyxPO[[$2jW#+Vg;Paj2ycIj8VUr5z1,}qR~JnK7r_0@$ov'
printf '%s' "$s" | cryptsetup luksOpen

In both cases, we don't use echo when we care about byte-for-byte perfect output.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • ... and if the OP has a single quote ' in the expression ... this will still work without a backslash escape ?! – M__ Aug 30 '19 at 15:25
  • Inside single quotes, *everything except another single quote* is literal (meaning, evaluating exactly to itself). – Charles Duffy Aug 30 '19 at 15:26
  • 2
    Note that there are two separate problems solved here, *setting* the variable correctly (as above, single quotes are usually simplest, but it depends on what special characters are in the string), and *printing* the variable correctly (`printf` is almost always the right answer here). – Gordon Davisson Aug 30 '19 at 16:43