User environment variables when running sudo

by vs
GNU/Linux ◆ xterm-256color ◆ bash 2817 views

This example shows how you need to add an -E to pass the user environment when using sudo. If you don’t, the variables will be undefined. E.g., given this script

  #!/bin/bash

  echo "SINGULARITY_USERNAME is set to ${SINGULARITY_USERNAME}"
  echo "SINGULARITY_PASSWORD is set to ${SINGULARITY_PASSWORD}"

If you run it as /test_environment.sh and the variables are defined, you will see them!

  SINGULARITY_USERNAME is set to vanessasaur
  SINGULARITY_PASSWORD is set to omgwtftacos

If you use sudo, sudo ./test_environment.sh you will not!

  SINGULARITY_USERNAME is set to 
  SINGULARITY_PASSWORD is set to 

The fix is to run (with sudo) adding the -E parameter sudo -E ./test_environment.sh

and then you will have the variables defined!

  SINGULARITY_USERNAME is set to vanessasaur
  SINGULARITY_PASSWORD is set to omgwtftacos