0

In a path, you can use relative and absolute paths.

  • /: Root directory
  • ./: Current directory
  • ../: Parent directory

But when you don't use a leading slash e.g. cd path/to/dir it acts like you're using cd ./path/to/dir.

Is there a difference? If no, what is the purpose of ./ when it works like the same without it?

puncher
  • 105
  • While I can make assumptions, can you please specify the OS(es) and applications you are asking about. Please make your question as complete as you can, making free use of the EDIT button. – music2myear Feb 23 '23 at 19:24

2 Answers2

1

There's no difference for standard file access. Paths like ./foo are valid because . as a path component is valid, and there is no need to deliberately make them invalid, thus they remain valid even if you're not required to use the ./ variant.

There is a difference for cd specifically: paths like foo and foo/bar aren't guaranteed to refer to the current directory when cd'ing to them – the shell will additionally try to resolve them using $CDPATH, whereas paths that are explicitly anchored using ./ will not do that. This is quite similar to $PATH lookup for executables.

Other programs may also have different treatment for bare filenames (often similarly performing a path search for names that don't contain a /). As a different example, "systemd-tmpfiles foo.conf" will look for foo.conf in the standard system directories – not in the current directory.

The ability to use ./ ends up being useful in other ways. In particular, because such a path starts with ., that means it doesn't start with - or @ or other possibly special characters; e.g. you can rm a path like ./--help.

(It is also useful for writing generic code that concatenates paths, e.g. $dir/foo still works as intended if you set $dir to ., without the need to have a special case for the current directory.)

u1686_grawity
  • 452,512
1

When you use ./, you are declaring that you refer to a file from the current folder. When you use path without it, you might not have intended for the command to be executed from the current folder.

In the early Linux days, developers were worried by malware masquerading its programs as standard Linux apps in the current folder. For example, if you used su and it was found in the current folder and stole your login and password.

Several Linux distributions will still not accept, as a precaution, to execute programs from the current folder without the addition of .\ in front of the executable's name. (I have been bitten so more than once.)

harrymc
  • 480,290