Search code examples
bashshellcommand-linecdunset

unset $HOME but '~' works has home anyway why?


Doing my own shell

Hello, I'm doing my own version of shell and comparing it to bash (School Project). I noticed that when i run the following command unset HOME; cd or unset HOME; cd $HOME it says:

bash: cd: HOME not set

Okay all good for me but.. with this command cd ~ bash goes to my home dir or when i run echo ~ it prints my home dir.

So how do you guys deal with this? I just coded it in a way that says:

bash: cd: HOME not set

Solution

  • From the man page for bash: (emphasis added)

    Tilde Expansion

    If a word begins with an unquoted tilde character (`~'), all of the characters preceding the first unquoted slash (or all characters, if there is no unquoted slash) are considered a tilde-prefix. If none of the characters in the tilde-prefix are quoted, the characters in the tilde-prefix following the tilde are treated as a possible login name. If this login name is the null string, the tilde is replaced with the value of the shell parameter HOME. If HOME is unset, the home directory of the user executing the shell is substituted instead. Otherwise, the tilde-prefix is replaced with the home directory associated with the specified login name.