~/.bash_profile失效

环境变量准备

在~/.bash_profile下配置了环境变量相关的路径信息,比如$HOME/bin路径。就是说会把$HOME/bin目录下的命令添加到环境变量中去。

# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
        . ~/.bashrc
fi

# User specific environment and startup programs

PATH=$PATH:$HOME/.local/bin:$HOME/bin
export PATH
交代一下背景情况:

创建了一台虚拟机,里面有多个账户,比如有tenic/hadoop账户,在hadoop账户下边的$HOME目录下的bin文件夹下创建了一个命令,
且命令有在hadoop用户的~/.bash_profile中定义环境变量到相应的bin路径。
使用secureCRT/xshell登录到虚拟机时使用的是tenic,然后切换到hadoop用户。执行hadoop用户bin目录下的命令时,提示命令不存在的问题。

解决方法一:

su 是最简单的用户切换命令,通过该命令可以实现任何身份的切换,包括从普通用户切换为 root 用户、从 root 用户切换为普通用户以及普通用户之间的切换。
我们看一下su的帮助信息

hadoop@hadoop01 ~]$ su --help

Usage:
 su [options] [-] [USER [arg]...]

Change the effective user id and group id to that of USER.
A mere - implies -l.   If USER not given, assume root.

Options:
 -m, -p, --preserve-environment  do not reset environment variables
 -g, --group <group>             specify the primary group
 -G, --supp-group <group>        specify a supplemental group

 -, -l, --login                  make the shell a login shell
 -c, --command <command>         pass a single command to the shell with -c
 --session-command <command>     pass a single command to the shell with -c
                                 and do not create a new session
 -f, --fast                      pass -f to the shell (for csh or tcsh)
 -s, --shell <shell>             run shell if /etc/shells allows it

 -h, --help     display this help and exit
 -V, --version  output version information and exit

For more details see su(1).

从帮助文档中可以看到,su后边可以添加多个可选入参,其中有一个 [-] 表示shell也跟着一起变更,
也就是说使用 [-] 选项表示在切换用户身份的同时,连当前使用的环境变量也切换成指定用户的。

解决方法二:

我们在2个用户的/.bashrc文件下添加一个echo语句,可以查看到,当切换用户不使用[-]时,会加载切换用户的/.bashrc环境变量,
所以我们可以在~/.bashrc文件中添加上我们想要添加的环境变量。如下边的图所示:


我们在我们想要切换的用户的~/.bahsrc中添加上相应的环境变量路径上去就可以了。

从我们打印出的$PATH路径可以看出,目前环境变量信息已经添加上我们切换用户的路径了。

posted @ 2021-04-11 19:09  Tenic  阅读(567)  评论(0编辑  收藏  举报