0

I want to use the touch command in linux terminal in order to create a file with a name that begins with the symbol -, say -attempt.

How can I overcome the the fact that - is a special character?

For example, if I wanted to create a file with the name #attempt, I couldnt just write touch #attempt

Instead I would have to write touch \#attempt, but in the - case even if I use \ it still does not work well).

ilkkachu
  • 138,973
FreeZe
  • 103
  • 4

2 Answers2

4

Two ways:

Move the -away from the first character

touch ./-foo

Or use the -- end-of-switches marker

touch -- -foo
waltinator
  • 4,865
3

touch \#attempt works because the hash sign is special to the shell. Similarly, you'd need something like touch \(foo\), or touch 'this & that' for filenames with parenthesis or ampersands etc.

But escaping the dash does not help since it's not special to the shell, but to the utility launched by the shell. Running the shell command line touch \-foo is just the same as running touch -foo, touch will get the single argument -foo anyway.

So, instead of escaping, something else is required.

The standard way to tell a program to stop interpreting command arguments as (possible) options, is to insert the argument -- after the options. E.g. this would run rm with the option -f, on a file called -r:

rm -f -- -r

(and rm -- -- would remove a file called --.)

Alternatively, you can work around the issue by making sure the dash is not the first character of the filename, usually by prepending ./. So again, this would remove a file called -rf:

rm ./-rf
ilkkachu
  • 138,973