How to read dash files

How can I read a dash file from the terminal other than delimiting it with ./

For example to read a - file we can read it by

cat ./-file_name

Q: Is there an alternative way to achieve the same thing?

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

Use double -- to mark end of options:

cat -- -<FILENAME>

Other programs such as touch, rm or git checkout also follow this convention:

$ touch -- -file
$ ll
total 0
-rw-r--r-- 1 ja ja 0 Mar 10 13:13 -file
$ echo hi! >> -file
$ cat -- -file
hi!
$ rm -- -file
$ echo $?
0

WARNING: It’s good practice to always use -- after rm in scripts. An attacker could place --rf file in a directory and rm * would take it as run parameters. See this:

$ touch A
$ touch B
$ mkdir dir
$ touch dir/C
$ touch -- -rf
$ rm *
$ ll
total 0
-rw-r--r-- 1 ja ja 0 Mar 10 13:21 -rf

Oops, this is not we meant, we didn’t want to remove directories. We should have used --:

$ touch A
$ touch B
$ mkdir dir
$ touch dir/C
$ touch -- -rf
$ rm -- *
rm: cannot remove `dir': Is a directory
$ ll
total 4.0K
drwxr-xr-x 2 ja ja 4.0K Mar 10 13:22 dir

Method 2

For commands which get input from stdin, you can use redirection:

cat <-file_name

Method 3

Alternatives become weird:

dd if=-x 2>/dev/null


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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x