I am making a dialog menu for an Ubuntu VPN that is calling up other scripts like this:

cd myrepo/gui

The first cd is to ensure the directory for the second cd is always home.

Is there a better method I can use to address this in one line? (Without specifically naming the user in the path, so it can be installed and used on a few devices?)

up vote 6 down vote accepted

~ (tilde) or $HOME can be used for getting the current user's home directory, so you could do:

cd ~/myrepo/gui
cd "$HOME/myrepo/gui"

Or even execute it directly:

  • 2
    If filetocall.sh expects the CWD to be ~/myrepo/gui then executing it directly could cause issues. Doing the cd and the executable call in two steps would prevent that. – Kevin Johnson Nov 17 at 18:16
  • 2
    @KevinJohnson That's true, though I would consider that to be a bug in filetocall.sh. – kasperd Nov 17 at 22:32

Use the same method used by login, which avoids being fooled by redefinitions of $HOME:

homedir="$(getent passwd $( /usr/bin/id -u ) | cut -d: -f6)"
cd "$homedir"
  • Lovely code, thankyou! – user797940 Nov 17 at 16:15
  • 1
    What about redefinitions of $USER? Maybe homedir="$(getent passwd -- "$(whoami)" | cut -d: -f6)" ? – wjandrea Nov 17 at 19:26
  • 4
    Well, it's not like I redefine $HOME often, but when I do it, it's precisely because I want scripts like this one to use that directory instead... – Federico Poloni Nov 17 at 21:33
  • @FedericoPoloni For exactly that reason I voted on Aviendha's answer. – kasperd Nov 17 at 22:40

cd ~/myrepo/gui will do the trick, or a little longer: cd $HOME/myrepo/gui.

~ is a shell shortcut for users home directory, $HOME is a variable set by th shell for the same.

  • 5
    Technically, it's the other way around - ~ is a shortcut for $HOME. If you set HOME to something, then ~ will take that value (test with (HOME=foo; echo ~) for example). – Aviendha Nov 17 at 14:38

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.