Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|improve this question
add comment

2 Answers

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.)

share|improve this answer
1  
Do you know this by heart or did you really go the extra mile? –  slhck May 20 '13 at 9:49
3  
I had the shells already installed, so... –  grawity May 20 '13 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 Jul 13 '13 at 22:19
add comment

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.
share|improve this answer
2  
perfect cause i wanna go home :( –  Belmark Caday May 20 '13 at 9:11
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.