For years, I've been grappling with this limitation in Bash: not being able to execute a script and update my parent shell's environment variables directly. This issue has been a constant annoyance. Then it hit me, I devised a workaround. It's not perfect, and admittedly, it's a bit of a hack, but it effectively simulates what seemed impossible. If you're able to modify the user's .bashrc, you can cleverly fake direct script execution and dynamic environment configuration. Here's how you can set it up:
Step 1: Create the env_setup.sh Files
Before setting up functions and aliases in your .bashrc, ensure that the env_setup.sh scripts exist in the locations you plan to manage them from, whether it's in specific project directories or more globally accessible locations in your PATH.
Create a basic env_setup.sh script with necessary environment variable exports:
# Example env_setup.sh
export PATH="/usr/local/bin:$PATH"
export MY_ENV_VAR="some_value"
Save this script in the directories where you frequently work, or place it in a directory that's part of your system's PATH to ensure it's universally accessible.
Step 2: Define Functions
To begin, you need to define two functions in your .bashrc file. These functions are crucial for managing the sourcing of scripts, whether they're in the current directory or elsewhere in your system's PATH.
Open your .bashrc in a text editor:
vim ~/.bashrc
Add the following functions:
# Function to source a script from the current directory
env_setup_func_dot() {
if [ -f "./env_setup.sh" ]; then
source ./env_setup.sh
else
echo "env_setup.sh not found in the current directory!"
return 1
fi
}
Function to search and source the script from the PATH
env_setup_func_nodot() {
local script_path=$(which env_setup.sh)
if [ -n "$script_path" ]; then
source "$script_path"
else
echo "env_setup.sh not found in the PATH!"
return 1
fi
}
Step 3: Create Aliases
Setting up aliases that users can call as if they were actual scripts enhances usability. Here’s how you can set these aliases:
alias ./env_setup.sh='env_setup_func_dot'
alias env_setup.sh='env_setup_func_nodot'
Step 4: Reload .bashrc
To apply these changes and make the functions and aliases available in your current session, reload your .bashrc:
source ~/.bashrc
With this setup, you can effectively mimic executing scripts directly and managing the shell environment in ways that originally seemed off-limits.
Considerations
Using dots in alias names is unconventional and may lead to confusion, as it's easy to mistake such aliases for file names or commands typically reserved for executables or scripts. While this setup works technically, it's essential to ensure that such usage is clearly documented if shared in a collaborative environment or deployed in a production setting.
mktempis elegance in its purest form. ;) – dessert May 15 '18 at 12:00