2

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

cd
cd myrepo/gui
./filetocall.sh

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

wjandrea
  • 14,236
  • 4
  • 48
  • 98

3 Answers3

6

~ (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:

~/myrepo/gui/filetocall.sh
"$HOME"/myrepo/gui/filetocall.sh
  • 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 '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
6

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"
waltinator
  • 36,399
3

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.

Soren A
  • 6,799
  • 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). –  Nov 17 '18 at 14:38