Search code examples
bashspecial-characters

How to escape special characters when echoing variable in Bash script?


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.


Solution

  • 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.