如何启动一个没有任何用户配置的 shell?

我需要在 Linux/OSX 终端下使用一个“干净”的 shell (例如 bash) ,不需要任何用户配置,但它可以从一些文件(例如:。每次开始的时候。我可以在每次需要一个“干净的”shell 时修改文件,并在完成后恢复它,但是有没有更简单的方法来做到这一点,例如使用命令?

36541 次浏览

You can pass the --noprofile and --norc command-line options:

$ bash --noprofile --norc

You will find documentation about these options in the man page.

Use --noprofile --norc:

   --noprofile
Do  not  read either the system-wide startup file /etc/profile or any of the personal initializa‐
tion files ~/.bash_profile, ~/.bash_login, or ~/.profile.  By default,  bash  reads  these  files
when it is invoked as a login shell (see INVOCATION below).


--norc Do  not  read  and  execute the system wide initialization file /etc/bash.bashrc and the personal
initialization file ~/.bashrc if the shell is interactive.  This option is on by default  if  the
shell is invoked as sh.

(from the manpage).

Running bash --noprofile --norc still inherited from parent process. Based on a similar question I found that the way I interpreted this question env -i bash --norc --noprofile was what I would want.

It is often desirable to launch an entirely blank bash:

  • no environment variables carried from the parent shell;
  • an empty home dir without any package-specific configuration files (e.g. .gitconfig and .local/...);
  • no shell configuration files.

This works for me both on MacOS and Linux:

env -i HOME=$(mktemp -d) bash --noprofile --norc
cd

In that bash shell, the HOME dir is that test dir just created (change the name if needed), and there are no particular settings. The only environment variables that are set are PWD, HOME, and SHLVL.

Upon starting bash, the PWD is where we were before, so we need to do that initial cd.

Example (Linux):

$ env -i HOME=$(mktemp -d) bash --noprofile --norc
bash-5.0$ cd
bash-5.0$ pwd
/tmp/tmp.mwgHRQE1aJ
bash-5.0$ printenv
PWD=/tmp/tmp.mwgHRQE1aJ
HOME=/tmp/tmp.mwgHRQE1aJ
SHLVL=1
OLDPWD=/home/xxxxxxxxxxxxxxxxx
_=/usr/bin/printenv
bash-5.0$