Escaping Special Characters in Linux and Unix: With 7 Practical Examples

I have written this short article on escaping special characters here. In this article I will show you how to escape the special characters, with 7 practical examples:

The escape character is \ .

Example 1:

I will create the file called one\2.

$ touch one\2
$ ls

The \ character is a special character (and also the escape character), so I need to escape it, in order to use it in the filename: touch one\\2

$ touch one\\2
one2 one\2

This also works: touch “one\2”.

Example 2:

Create file or folder containing space in name:

$ touch a b
$ ls -1

Also the space character is a special one and it has to pe escaped: touch a\ b

$ touch a\ b
ls -1
a b

This also works: touch “a b”.

Example 3:

Create files with double quotes in the filenames:

$ touch "one"
$ ls

$ touch ""one""
$ ls

Escape the double quotes in order to use them in filenames: touch \“one\

$ touch \"one\"
$ ls

Also, this works: touch ‘”one”‘

Example 4:

Create files with single quotes inside the filenames: touch \‘one\

$ touch \'one\'

Example 5:

As you know, the & character send the process in backgroup. So, how to create a file called file& ?

$ touch file&
[1] 11267

$ touch file\&

Also, this works: touch ‘file&’ or touch “file&”

Example 6:

cd into a directory having space in name (no tab completion allowed!!!): cd star\ wars ; cd ../rock\ n\ roll

$ ls -1
rock n roll
star wars
$ cd star wars
-bash: cd: star: No such file or directory

$ cd star\ wars
$ pwd
/home/razvan/workdir1/star wars
$ cd ../rock\ n\ roll
$ pwd
/home/razvan/workdir1/rock n roll

Example 7:

Making an alias persistent:

I have this alias: alias test=’echo “test two”‘ and want to make it persistent (add it to ~/.bashrc).

$ echo 'alias test='\'echo \"test\ two\"\''' >> ~/.bashrc
$ grep test ~/.bashrc
alias test='echo "test two"'

In order to make append the needed text in the ~/.bashrc file, I had to escape the single quotes, the double quotes and the space character.

Tagged with: , , , , , ,
Posted in The Linux and Unix Articles!

Leave a Reply

Your email address will not be published. Required fields are marked *




Subscribe to get the latest Linux news and how to guides directly on your e-mail!