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 \ .
I will create the file called one\2.
$ touch one\2
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
This also works: touch “one\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
This also works: touch “a b”.
Create files with double quotes in the filenames:
$ touch "one"
$ touch ""one""
Escape the double quotes in order to use them in filenames: touch \“one\“
$ touch \"one\"
Also, this works: touch ‘”one”‘
Create files with single quotes inside the filenames: touch \‘one\‘
$ touch \'one\'
As you know, the & character send the process in backgroup. So, how to create a file called file& ?
$ touch file&
$ touch file\&
Also, this works: touch ‘file&’ or touch “file&”
cd into a directory having space in name (no tab completion allowed!!!): cd star\ wars ; cd ../rock\ n\ roll
$ ls -1
rock n roll
$ cd star wars
-bash: cd: star: No such file or directory
$ cd star\ wars
$ cd ../rock\ n\ roll
/home/razvan/workdir1/rock n roll
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.