vinod vinod - 4 months ago 6x
Bash Question

How to get the special characters as a normal string in shell

I have written a shell script which reads a file and take the path of a file required to perform particular task but if the path of the file contains any special characters it is not taking the complete path

for eg the path is \web\take\ab
the value i am getting is \web ake\ab here it is treating \t as tab and printing the tab so how to avoid this

My code is

grep "Cannot " input.txt | cut -f 2,3 -d":"

echo $grepresult

So please help how can I get the special characters into the string


In POSIX compliant shells,with some exceptions, the interpretation of backslash is by default enabled.

The problem as you know is that, shell interprets \ with its special meaning.To have the backslash in the output, simply backslash it.


$ grepresult="sometestt\n\b\a"


echo  "${grepresult//\\/\\\\}"
#since \ has special meaning here as well, `\\` makes the character `\`

should do the trick. Look for ${var//Pattern/Replacement} in Shell Parameter Substitution.


$ echo  "${grepresult//\\/\\\\}"

Also good to check Treatment of backslashes across shells.