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,109
  • 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
  • 35,099
  • 19
  • 57
  • 93
  • 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... – Federico Poloni Nov 17 '18 at 21:33
  • @FedericoPoloni For exactly that reason I voted on [Aviendha](https://askubuntu.com/users/894105/aviendha)'s [answer](https://askubuntu.com/a/1093700/284919). – kasperd Nov 17 '18 at 22:40
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,442
  • 2
  • 17
  • 33
  • 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