15

I was messing around with environment variables on my Mac, trying to learn how to use them and I used the command nano ~/.bash_profile where I then added the line HOME=/Users/MyCompName/Desktop to update my home variable.

This change worked and can be seen when I use printenv to view all environment variables but when I went to change HOME back I couldn't seem to find ~/.bash_profile anymore. Where did it go?

  • 9
    Basically ~ means $HOME – el.pescado Oct 8 '18 at 7:08
  • 6
    ...so if you redefine $HOME, ~gets redefined too – el.pescado Oct 8 '18 at 10:49
32

It's in the same place.

Before the change ~ expands to something like /Users/YourUserName, the shell finds your .bash_profile there. After the file gets sourced ~ expands to another path so ~/.bash_profile no longer points to the relevant file. This is because in this context ~ means $HOME.

If you know the full path to your actual home directory, you can use it instead of ~. In Mac it would probably look like this:

nano /Users/YourUserName/.bash_profile

Or let your Bash look up your home directory in the user database rather than just looking at $HOME. This doesn't require you to remember anything:

nano ~YourUserName/.bash_profile

Modifying your HOME variable without changing your actual home directory is not the best idea. Changing any user's home directory is an administrative task, usually regular users cannot do this.

  • Awesome I was able to find it again thanks! Would you mind elaborating on what you mean by "after the file gets sourced"? I'm unfamiliar with what it means for a file to get sourced – Matt Oct 8 '18 at 6:16
  • 6
    @Matt .bash_profile has a form of a Bash script. You can run a script or source it. Running means creating a subshell and executing the script line by line there. Sourcing means executing the script in the current shell. Some tasks that are meant to affect the current shell cannot be executed in a subshell; changing a variable for the current shell is one of them. That's why some files are sourced, not executed in a subshell. To manually source a file use . file (. is specified by POSIX) or source file (source is a non-POSIX extension understood by few shells). – Kamil Maciorowski Oct 8 '18 at 6:22
  • 4
  • 2
    If you(Matt) don't know where your home directory used to be, you can use nano ~YourUserName/.bash_profile instead. This will look up your home directory in the user database rather than just looking at $HOME. – Stig Hemmer Oct 8 '18 at 8:34
  • 1
    @StigHemmer The answer is now community wiki. Your useful comment has been assimilated. Thank you. – Kamil Maciorowski Oct 8 '18 at 9:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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