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


~ (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. Nov 17 '18 at 18:16
  • 2
    @KevinJohnson That's true, though I would consider that to be a bug in filetocall.sh.
    – kasperd
    Nov 17 '18 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"
  • 1
    What about redefinitions of $USER? Maybe homedir="$(getent passwd -- "$(whoami)" | cut -d: -f6)" ?
    – wjandrea
    Nov 17 '18 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... Nov 17 '18 at 21:33
  • @FedericoPoloni For exactly that reason I voted on Aviendha's answer.
    – kasperd
    Nov 17 '18 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).
    – user894105
    Nov 17 '18 at 14:38

Your Answer

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