BASH Variables are scoped. This means they are only available to certain things and not shared system-wide.
When you instantiate a variable, it is available for the current shell (x="apple"
). When you export, that variable is available in the current shell, and subsequent shells/functions (export x="apple"
). If you close that shell/terminal, you lose that variable.
For this reason, common variables are added to user profiles so that they are loaded properly. This is typically done using export
in ~/.bashrc
or ~/.bash_profile
.
Similar to how the variable is lost if you close your terminal, these variables are lost if you switch users.
If you want root
to have access to a BASH variable, you have to declare the variable within the root
shell. You can duplicate your (assumed) export
s in your ~/.bashrc
into the root
user's /root/.bashrc
file, and have that sourced properly.
You may be able to export/push all variables by looking at man sudo
(look at -E
), as I know it has a few options on whether to switch to the new user's directory and possibly share variables, but this isn't the approach I would take.
Instead, similar to how you'd share a web server directory (/srv/www/
) by having a shared group own the file (www-data
, g+rwx
), and making sure only that group can read the file (o-rwx
), we will create a shared file to source and secure against unauthorized users. So, you can add the following to each user's ~/.bashrc
file that is in the group and you want to have access to the variable:
$ touch /srv/www/.bashrc_shared
$ chown www-data:www-data /srv/www/.bashrc_shared
$ chmod g+rwx /srv/www/.bashrc_shared
$ chmod o-rwx /srv/www/.bashrc_shared
$ vim /srv/www/.bashrc_shared
#!/bin/bash
export MY_SECRET_VAR="super_secret_var"
Now, ensure ~/.profile
sources this file, or your ~/.bashrc
which then sources this file, or run sudo
with the -i
flag:
cat ~/.profile
# ~/.profile
#
[[ -f /srv/www/.bashrc_shared ]] && source /srv/www/.bashrc_shared
OR
sudo -i your_command # Source config files