Skip to content

Commit

Permalink
Merge pull request #4685 from Micket/fix_unset
Browse files Browse the repository at this point in the history
Use more robust mechanism for unsetting environment variables
  • Loading branch information
boegel authored Oct 16, 2024
2 parents 2ebaa47 + 46102d3 commit 3716f43
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
15 changes: 13 additions & 2 deletions easybuild/tools/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,8 +234,19 @@ def create_cmd_scripts(cmd_str, work_dir, env, tmpdir, out_file, err_file):
with open(env_fp, 'w') as fid:
# unset all environment variables in current environment first to start from a clean slate;
# we need to be careful to filter out functions definitions, so first undefine those
fid.write("unset -f $(env | grep '%=' | cut -f1 -d'%' | sed 's/BASH_FUNC_//g')\n")
fid.write("unset $(env | cut -f1 -d=)\n")
fid.write('\n'.join([
'for var in $(compgen -e); do',
' unset "$var"',
'done',
]) + '\n')
# also unset any bash functions
fid.write('\n'.join([
'for func in $(compgen -A function); do',
' if [[ $func != _* ]]; then',
' unset -f "$func"',
' fi',
'done',
]) + '\n')

# excludes bash functions (environment variables ending with %)
fid.write('\n'.join(f'export {key}={shlex.quote(value)}' for key, value in sorted(env.items())
Expand Down
3 changes: 2 additions & 1 deletion test/framework/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,8 @@ def test_run_shell_cmd_env(self):
env_script = os.path.join(cmd_tmpdir, 'env.sh')
self.assertExists(env_script)
env_script_txt = read_file(env_script)
self.assertTrue(env_script_txt.startswith('unset -f $('))
self.assertIn('unset "$var"', env_script_txt)
self.assertIn('unset -f "$func"', env_script_txt)
self.assertIn('\nexport FOOBAR=foobar\nexport PATH', env_script_txt)

cmd_script = os.path.join(cmd_tmpdir, 'cmd.sh')
Expand Down

0 comments on commit 3716f43

Please sign in to comment.