Super User Asked by dgo.a on December 7, 2021
Is there a way to run a command "as if" it is in a new login session?
I’ve already tried env -i
. However, I don’t want to deal with various ENV variables I have to set or unset.
I’ve also tried bash -c "some command"
and bash -l -c "some commmand"
, but they all copy the current environment.
The closest I have come is a not-so-clean solution:
ssh me@localhost "some command"`
Here's an answer that doesn't require sudo privileges or the user's password, but still provides an environment like what you'd get on a fresh login.
env -i HOME="$HOME" bash -l -c 'your_command'
Example:
$ export ABC=123
$ env -i HOME="$HOME" bash -l -c 'env' | grep ABC
$ env HOME="$HOME" bash -l -c 'env' | grep ABC
ABC=123
Breaking this down for explanation:
env -i HOME="$HOME"
: Clears the environment. The -i
sets up an empty environment with no variables whatsoever. This is problematic because it means that if you try to naively run bash -l
it won't load your .bash_profile
etc. because HOME
isn't set. To mitigate this, we explicitly pass HOME="$HOME"
, creating an environment where HOME
(and only HOME
) is set.
bash -l -c ...
: Runs the desired command in a login shell. You'll want a login shell for this because we're starting from a clean environment and need to reload everything.
Notably:
sudo
version does).su
version does).ssh
version does).Answered by Elliott Slaughter on December 7, 2021
su -l $USER
sudo -u $USER -i
For something even more aggressive try env -i bash
, but that unsets everything including $HOME and $TERM.
Answered by user1686 on December 7, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP