In places that expect a path to a file, ./foo
is equivalent to foo
. There are only a few places where writing ./foo
is useful.
Writing ./foo
is useful when what is expected is not necessarily a path, but possibly a file name that may be looked up in a search path. The most common case is when invoking an executable command. Executable programs are searched in directories listed in the PATH
variable, but this lookup is only performed if the given command name does not contain a slash. So ls
invokes the ls
command found in the PATH (typically /bin/ls
), whereas ./ls
invokes the executable program ls
in the current directory. More generally, writing ./foo
also bypasses any shell alias, function or builtin called foo
.
Another use for the ./
prefix is to avoid trouble with file names starting with some special characters. In particular, when you pass a file name as an argument to a command, in most cases, the command allows options starting with -
. If the file name comes from a variable, you may not be sure that the file name doesn't start with -
. Writing "./$filename"
instead of "$filename"
ensures that it won't be misinterpreted as an option if it starts with -
. However this only works if $filename
is a relative path (i.e. not beginning with /
). Another more general method of protecting file names is to put them after --
on the command line: mycommand -- "$filename"
(--
conventionally indicates that what follows are non-option arguments only) (however this doesn't always work in one specific case: if $filename
is -
, many commands treat that as meaning “standard input”). On this topic, see also Why does my shell script choke on whitespace or other special characters? and Security implications of forgetting to quote a variable in bash/POSIX shells
cd ./bar
isn't always equivalent tocd bar
: the./
bypassesCDPATH
– Gilles 'SO- stop being evil' Feb 11 '16 at 00:19