Difference in cd.. and cd .. (Change Directory) [duplicate]

Posted on

Problem :

cd.. and cd ...

Basically, they are doing the same. But, who and why thought of changing it with space or without space? Why is there space and why there isn’t space between cd and two dots?

C:WindowsSystem32>cd..

and

[bla/www/something/something]#cd ..

They are both the same. Why one has space, and another hasn’t?

EDIT:

It’s not duplicate of this question:.

Why does “cd..” work in the Windows command line?

Solution :

On UNIX-like systems, the shell sh separates what you type into words and passes each word separately as an argument to the program or builtin-command referred to by the first word (the command name itself is the zeroth argument). Simplified, words are split on every space. Thus,

cd ..

is two words but

cd..

is only one. There is no command named cd.. on UNIX, thus the latter fails. The former invokes cd with the single argument .., changing one directory up. For a more complicated example,

echo foo bar  baz   quux

is parsed into the four words echo, foo, bar, baz, and quux which are then passed to the echo command as its arguments. The amount of whit espace in between is lost, and echo will print

foo bar baz quux

as it always inserts a single blank between each argument.

On Windows, DOS and CP/M, the shell COMMAND.COM parses the command name as the longest prefix of what you typed until a space or punctuation is reached (This too is a simplification). Then the command is executed with the entire line you typed as the argument. A pointer indicates where the command interpreter believes the command name ended. COMMAND.COM does not split the command line into arguments, if the program desires that to happen, it has to do so itself.

For example, in cd .. the shell decides that cd is the command name, which happens to be a builtin command. The builtin command is executed with the argument string being cd .. and the information that the first two characters form the command name. Similarly, for cd.. the shell decides that cd is the command name and passes .. as the operand name. The cd command skips the command name, trims the rest from white space and then tries to change into the directory mentioned.

Similarly for,

echo foo bar  baz   quux

the shell invokes the echo command with echo foo bar baz quux as the arguments and echo duly prints

foo bar  baz   quux

This is the reason why cd.. works in DOS but not on UNIX.

Both designs have their pros and cons, though the UNIX-style has taken over almost all systems as it is much easier to program against as only one program (the shell) needs to know how to split a command line into words as opposed to every program having its own home-cooked solution.