1

Im attempting to run a command as root but it is not working and I think the reason why is because when running the command sudo is not setting $HOME to /root but keeping it as /home/MYUSER the command im running is:

$ sudo -H -u root bash -c "echo $HOME"
/home/MYUSER

Ive also tried the following which results in the same:

sudo su -c "echo $HOME" root

Note the actual issue im having is trying to run kubectl commands which MYUSER does not have access to do so the command im actually trying to execute is:

sudo -H -u root bash -c "kubectl get pods"
[sudo] password for MYUSER:
The connection to the server localhost:8080 was refused - did you specify the right host or port?

I think the issue is the $HOME thing because /root has the .kube directory but /home/MYUSER does not.

TheQAGuy
  • 113

1 Answers1

2

Double quotes permit the interactive shell to expand $HOME before passing the arguments to sudo bash. You can verify this by setting your shell into debug mode:

$ set -x
$ sudo bash -c "echo $HOME"
+ sudo bash -c 'echo /home/steeldriver'
/home/steeldriver
$ set +x

Try instead

sudo -H -u root bash -c 'echo $HOME'

or just plain

sudo bash -c 'echo $HOME'

since -H is the default in currently supported Ubuntu versions. See also:

steeldriver
  • 136,215
  • 21
  • 243
  • 336
  • Wow such a simple fix. Thank you. – TheQAGuy Sep 01 '22 at 15:42
  • @TheQAGuy sorry it likely doesn't help with your kubectl command issue though – steeldriver Sep 01 '22 at 15:58
  • It does not but at least now I know that probably not the issue. I actually found a way to do it. Im doing echo -e "PASSWORD\n" | sudo -S sleep 1 && sudo -i -u root bash -c "export KUBECONFIG=/etc/kubernetes/admin.conf && kubectl get pods" which seems to work. – TheQAGuy Sep 01 '22 at 16:15