How to Escape a character in a Bash command String

If you try to echo a String as a Bash command or a Script that has a special character such as an exclamation mark, you will see that it will not work as intended or you get an error.

bash-3.2$ echo Hello World!
bash: !": event not found

Below is an extensive table that enlists the special characters and how to escape them with Bash String or Script.

Special Character Meaning How to Escape
" Double quote \"
' Single quote \'
$ Dollar sign \$
& Ampersand \&
( Left parenthesis \( or \)
) Right parenthesis \( or \)
{ Left curly brace \{
} Right curly brace \}
[ Left square bracket \[
] Right square bracket \]
! Exclamation mark \!
* Asterisk (wildcard) \*
? Question mark (wildcard) \?
\ Backslash \\
> Greater than sign (output redirection) \>
< Less than sign (input redirection) \<
; Semicolon (command separator) \;

Now let's make our "Hello World!" string work.

$ echo Hello World \!
Hello World

# echo <
bash: syntax error near unexpected token `newline'
# echo \<
How to escape special characters in bash

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap