Is there any difference between these (almost the same) directory commands?

1. cd
2. cd ~
3. cd ~/

I tried it in my shell, and they all lead to the home directory. Is there any possible scenario where they are different?


2 Answers 2


POSIX defines that...

  1. ...if cd was not given any arguments, it will use the value of $HOME if the variable is set, and do nothing otherwise (although it also says that results are unspecified). — cd

  2. ...if an argument is ~ or begins with ~/, the tilde will be expanded to the value of $HOME if the variable is set; the results are unspecified otherwise. — tilde expansion

So if $HOME is set, then all three commands are equivalent. (Extra slashes after directory names are meaningless.)

However, if $HOME is not set, then the results of both ~-expansion and cd are unspecified:

  • In bash, AT&T ksh, and Heirloom sh, plain cd will fail with "no home directory".

  • In csh, zsh, dash, and MirBSD mksh, plain cd will do nothing.

  • In tcsh, plain cd will look up the home directory using getpwuid().

As for the ~ expansion...

  • bash and tcsh will expand ~ to the home directory from getpwnam().

  • AT&T ksh will expand ~ to your username (?!).

  • In csh and zsh, ~ will expand to an empty string. (cd ~ will therefore do nothing, like plain cd, in those shells.)

  • In dash and MirBSD mksh, the ~ will remain a literal ~. (Using cd ~ will try to change to a directory named such.)

  • Heirloom sh never expands ~ even if $HOME is set – it probably predates the convention.

Out of these, only csh and zsh stick to the POSIX definition of expanding ~ to the value of $HOME even if it is empty.

(The fish shell always sets $HOME from getpwnam() on startup if the variable empty, and refuses to modify it afterwards.)

  • 1
    Do you know this by heart or did you really go the extra mile?
    – slhck
    Commented May 20, 2013 at 9:49
  • 3
    I had the shells already installed, so... Commented May 20, 2013 at 10:01
  • Your remark about AT&T's ksh expanding to the username reminded me of a neat trick in bash, dash and probably others: cd ~<username> will take you to <username>'s home.
    – GnP
    Commented Jul 13, 2013 at 22:19

Well, I can imagine a scenario where 1 is different to 2 and 3. Try defining the following function in bash:

cd () { if (($#)) ; then builtin cd "$1" ; else cd / ; fi ; }
  1. will take you to /, while 2. and 3. will take you home.
  • 2
    perfect cause i wanna go home :( Commented May 20, 2013 at 9:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .