The other day, I came across a rather unusual file. Its name was exactly `-rw-r--r--`, and it had apparently been created under some strange and unknown circumstances.
At first glance, it looks like a perfectly normal filename. But try to access or remove it using the usual commands, and you'll quickly discover that things don't work quite as expected.
The problem? Commands like `rm` and `ls` interpret a leading hyphen (`-`) as the beginning of a command-line option. Quoting the filename doesn't help because the command still sees it as an option rather than a filename.
Fortunately, there are a couple of simple ways to deal with files and directories like this. The approach is slightly different depending on your operating system, so let's have a look.
The problem
Here's the file in question:
shell@gz:~$ ls -la
total 0
drwxr-xr-x 2 root system 4096 Nov 03 09:00 .
drwxr-xr-x 4 root system 256 Jul 19 14:04 ..
-rw-r--r-- 1 root system 0 Nov 02 16:30 -rw-r--r--
You might think that putting the filename in quotes should do the trick. Unfortunately, it doesn't:
shell@gz:~$ rm -f '-rw-r--r--'
rm: Not a recognized flag: w
Usage: rm [-firRe] [--] File...
shell@gz:~$ ls -la "-rw-r--r--"
ls: Not a recognized flag: w
ls: Not a recognized flag: -
ls: Not a recognized flag: -
ls: Not a recognized flag: -
ls: Not a recognized flag: -
ls: Not a recognized flag: -
Usage: ls [-1ACFHLNRSabcdefgiklmnopqrstuxEUX] [File...]
As you can see, AIX interprets the filename as a collection of command-line options. Quoting it doesn't change that.
AIX: The simple solution
One of the easiest ways around this is to explicitly specify the current directory by adding `./` in front of the filename. You can also use its full path.
shell@gz:~$ ls -la ./-rw-r--r--
-rw-r--r-- 1 root system 0 Nov 02 16:30 ./-rw-r--r--
shell@gz:~$ rm ./-rw-r--r--
shell@gz:~$ ls -la ./-rw-r--r--
ls: 0653-341 The file ./-rw-r--r-- does not exist.
And that's it! The file is gone.
GNU/Linux: Another way
On GNU/Linux, you can use exactly the same `./` trick. However, there's another convenient option: `--`.
This special argument tells the command that there are no more options to process. Everything following it should be treated as an argument, even if it starts with a hyphen.
For example:
user@linux:~$ ls -la -- -rw-r--r--
-rw-r--r-- 1 user user 0 Nov 02 16:30 -rw-r--r--
user@linux:~$ rm -- -rw-r--r--
user@linux:~$ ls -la -- -rw-r--r--
ls: cannot access '-rw-r--r--': No such file or directory
Notice that you don't even need to prepend `./` when using `--`.
The same approach works with other GNU/Linux commands that support the `--` convention, although not every command implements it.
A small detail worth remembering
The next time you encounter a filename beginning with a hyphen, don't fight with quotes. Either explicitly specify its path using `./` or use `--` where supported.
A tiny detail, but one that can save you a bit of head-scratching!
- Log in to post comments
- 22309 views