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.
Test:
$ touch one\2
$ ls
one2
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:
Test:
$ touch a b
$ ls -1
a
b
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:
Test:
$ touch "one"
$ ls
one
$ touch ""one""
$ ls
one
Escape the double quotes in order to use them in filenames: touch \“one\“
$ touch \"one\"
$ ls
"one"
Also, this works: touch ‘”one”‘
Example 4:
Create files with single quotes inside the filenames: touch \‘one\‘
$ touch \'one\'
ls
'one'
Example 5:
As you know, the & character send the process in backgroup. So, how to create a file called file& ?
Test:
$ touch file&
[1] 11267
$ touch file\&
ls
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
Test:
$ 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.
Leave a Reply