I'm having a hard time getting what ./
does.
In the Linux Essentials books, it asks me in an exercise to delete a file named -file
. After googling, I found that I need to do rm ./-file
but I don't get why!
I'm having a hard time getting what ./
does.
In the Linux Essentials books, it asks me in an exercise to delete a file named -file
. After googling, I found that I need to do rm ./-file
but I don't get why!
The .
directory is the current directory. The directory ..
is the upper level of that directory
$ pwd
/home/user
$ cd docs; pwd # change to directory 'docs'
/home/user/docs
$ cd . ; pwd # we change to the '.' directory, therefore we'll stay. No change
/home/user/docs
$ cd .. ; pwd # back to up level
/home/user
In Linux, commands options are introduced by the -
sign, i.e., ls -l
, so if you want to make any reference to a file beginning with -
such as -file
, the command would think you are trying to specify an option. For example, if you want to remove it:
rm -file
will complain because it's trying to use the option file
of the command rm
. In this case you need to indicate where the file is. Being in the current directory, thus the .
directory, you need to refer to that file as ./-file
, meaning, in the directory .
, the file -file
. In this case the command rm
won't think that's an option.
rm ./-file
It can be done, also, using --
.
From man rm
:
To remove a file whose name starts with a '-', for example '-foo', use one of these commands:
rm -- -foo rm ./-foo
If you type rm -file
you will be passing a commandline option to rm
not the name -file
.
To delete -file
pass rm
the name in quotes rm "-file"
or escape the -
. rm \\-file
.
In either bash or zsh if you are unsure that a command is getting the proper filename use tab completion. Examples: type rm -fi
TAB if the screen does not printout rm -file
you know you did something wrong and should fix it before hitting return, another example rm "-fi
TAB should printout rm "-file"
.
As for ./
, /
is just the separator between directories and filenames. "." means present directory. ".." means the directory one up. So to delete the file foo
in the present directory type rm ./foo
( rm foo
is OK too ) to delete the file one directory up type rm ../foo
to delete the file in the directory bar
which is contained in the directory above type rm ../bar/foo
.
In this case ./
is put in front of -file
so that the -
character is not the first thing that rm
sees because that would make it think you are using some option.
If you know a bit of DOS, rm -file
would correspond to rm /file
in DOS.
. is the current directory. So e.g. ls
and ls .
are synonymous. If you are in /etc
the commands cat /etc/fstab/
, cat ./fstab
and cat fstab
do the same thing.
rm ./-file
is used because rm
parses everything starting with -
as command line options and not file names. For example ls -l
does not try to show file named -l
, but ls ./-l
and ls /some/directory/-l
do.