Escape special characters in BASH

There are some special characters in a shell, which otherwise may have meant something else if used anywhere else. But, just because we are using them in BASH. Then, it would lead to different outcomes. So, in this article, we would cover how to escape those special characters in BASH or use them as and when necessary.

Escape special characters in BASH

There are so many special characters, few of those commonly used include dollar sign($), asterisk(*), exclamation mark(!), question mark(?) etc. Now, let’s understand how these special characters can be interpreted differently by BASH.

So, if we want to do –

echo $SHELL

This will return with –


Even if we try to fit $SHELL in double quotes, it won’t work –

echo "$SHELL"

Again, the result will be same –


But, what if we actually wanted to display $SHELL. Then, in that case, we need to use backslash (\). What backslash (\) does is – it helps escape dollar sign ($). So, now see how the output changes when we use backslash (\) –

echo \$SHELL


echo "\$SHELL"

In both the cases, it would return with –


But, if we use single-quotes then it would interpreted differently.

echo '$SHELL'

The output –


That suggests, things may be different when using single and double-quotes for different special characters. Also, when backslash(\) precedes any character then, we make sure that the BASH interprets that particular character as it is.

In conclusion, we have discussed how to escape special characters in BASH. Although there could be numerous other combinations to explain with. But, we tried to cover the concept here.

Additional Info –

There is one more thing we think should be a part of the discussion here. And, that is newline character. Sometimes, we want to display a line of text and in between we insert a \n for newline somewhere. For instance,

echo "Hello\nWorld!"

It would return with the output –


This didn’t work because, by default echo disables backslash escapes interpretation. To enable it, we need to use -e option. So, the above command should be –

echo -e "Hello\nWorld!"

This time around, the output would be –


Similar Posts