I was working on a shell script and I accidentally created a file with the variable as its name. Now I have $file in my ls output, and cannot remove it. What can I do?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can escape the $ with :
rm $file
Method 2
You can also do
rm '$file'
Stuff in single quotes is taken as literal always,so globs and variables don’t get expanded.
Method 3
Basically, if you want to do things literal with these weird characters, you need to escape it. In a shell there are several ways to do that. The first one is to prepend a ‘’ to every character you want to escape. So you can do rm $file. Another way is to quote them with single quotes, for example, rm '$file' or rm '$'file. Some people also consider double quotes as a mean to “escape”, but it only escapes white spaces. For example if you have a file named a file, you can do
rm a file
or
rm 'a file'
or
rm "a file"
Method 4
If you ever accidentally create a file named -rf, you can use rm -- -rf to delete it.
Method 5
Any graphical file manager should be able to handle this through the context menu, because it doesn’t try to interpret anything.
Method 6
Some ways to get rid of files with weird names are to use globbing (i.e., rm ?file if the first character is something strange, but that would also nuke Xfile, need to be careful not to match too much, check with echo beforehand) and/or use the interactive flag: rm -i *file will ask for all stuff called somethingfile if you want to delete it.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0