3

Should I use dot to indicate the current directory for accessing directories or should I use it for files only?

For example, if the current directory is foo and it contains bar directory and baz.txt file, when can I omit the dot character?

./bar
./baz.txt

2 Answers2

3

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

2

Well, you can omit the dot caracter for folders if you wish but the both are OK

cd ./bar

or

cd bar

are equivalent - but you'll agree that the second is more convenient.

If you want to execute your bar.txt file (which may be executable with chmod 755 for example) then you have to use the ./ indicator

./bar.txt will execute the script

bar.txt will do nothing

cat bar.txt or cat ./bar.txt will do the same.

hope that help :)

EDIT: if you want to have more information about why ./ is needed to run script, just follow: https://stackoverflow.com/questions/6331075/why-do-you-need-dot-slash-before-script-name-to-run-it-in-bash

Because on Unix, usually, the current directory is not in $PATH. When you type a command the shell looks up a list of directories, as > specified by the PATH variable. The current directory is not in that list.

(@cnicutar)