Search code examples
bashcd

In Bash, is there any practical difference between cd ./someDir and cd someDir?


In a terminal, entering cd ./someDir and cd someDir achieves the same result, i.e. a change from the current directory to the someDir sub-directory.

In which situations would you use one over the other, or are the two commands exactly equivalent?

man cd doesn't shed much light on the question and I couldn't easily find documentation online. Are there docs covering this somewhere?

I'm running a standard shell in MacOS Catalina on VSCode, $SHELL --version reports GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin19)

This is my first question and I'm open to any feedback on how to improve it. Thanks.

Edit: This isn't related to a particular use case I've got, I'd just like to know if there's any actual difference between the commands.

It came up in a PR recently where I saw the cd ./ used, I asked whey they'd used that rather than cd by itself. They understood that the former "ensures it's constrained to the current directory" but weren't able to explain further.

On the face of it both commands are the same, but in Bash subtle differences can lead to different behaviour and I'd like to know whether that's the case here. Normally I'd use cd by itself. I understand . is a reference to the current directory.


Solution

  • is there any practical difference between cd ./someDir and cd someDir?

    Well, not on my accounts. But yes.

    In which situations would you use one over the other

    I would use any.

    , or are the two commands exactly equivalent?

    No.

    Are there docs covering this somewhere?

    From POSIX cd:

    1. If the first component of the directory operand is dot or dot-dot, proceed to step 6.

    2. Starting with the first pathname in the -separated pathnames of CDPATH (see the ENVIRONMENT VARIABLES section) if the pathname is non-null, test if the concatenation of that pathname, a character if that pathname did not end with a character, and the directory operand names a directory. If the pathname is null, test if the concatenation of dot, a character, and the operand names a directory. In either case, if the resulting string names an existing directory, set curpath to that string and proceed to step 7. Otherwise, repeat this step with the next pathname in CDPATH until all pathnames have been tested.

    3. ...

    So:

    $ mkdir -v -p a tmp/a
    mkdir: created directory 'a'
    mkdir: created directory 'tmp'
    mkdir: created directory 'tmp/a'
    $ CDPATH=$PWD/tmp
    

    then:

    $ cd a
    /some/path/tmp/a
    

    But:

    $ cd ./a
    $ pwd
    /some/path/a