Bash: Escape String Variable

Objective: Escape or append a ‘\’ to reserved characters (e.g &, \, |, ?, *, etc) found on a string variable in bash.

Before we look at the solution, let’s take a closer look at the problem. Suppose, we have a shell variable assigned as shown below.

Now, let’s try to use the variable in sed for search and replace. Let’s replace the occurrence of ‘__VAR__‘ to the contents of the variable $evar.

As you can see, the output is wrong. The output should be the contents of the variable $evar. We will need to escape the string found in the variable $evar before we pass it to sed.

The solution to insert escape sequences to the string variable is to use the shell builtin printf function with the “%q” format specifier as shown in the syntax below.

To use it within sed, use the following syntax.

This time, the output is the same as the contents of the variable.

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, php, python, java, javascript, nodejs, react); plays_on(xbox, ps4); linux_desktop_user(true); }