Home > Back-end >  Shell - Pass env variable to Python Script
Shell - Pass env variable to Python Script

Time:08-02

I have the shell script where I create a Python file on the fly:

#!/bin/bash

args=("$@")

GIT_PASSWORD=${args[0]}
export $GIT_PASSWORD

python - << EOF

import os

print(os.environ.get("GIT_PASSWORD"))
                                                         
EOF

echo $GIT_PASSWORD

echo "Back to bash"

I want to be able to access the variable GIT_PASSWORD, but unfortunately, I am not able to pass it to the python file.

Does anyone know what I am doing wrong and how I may fix that?

CodePudding user response:

The thing is that you're not actually setting an env variable, you need to change the export:

export GIT_PASSWORD=$GIT_PASSWORD

please do read the comment interaction below

CodePudding user response:

#!/bin/bash
while getopts 1: flag
do
        case "${flag}" in
                1) GIT_PASS=${OPTARG};;
        esac
done

export GIT_PASSWORD=$GIT_PASS

python - << EOF

import os

print(os.environ.get("GIT_PASSWORD"))
                                                         
EOF

echo $GIT_PASSWORD

echo "Back to bash"

CodePudding user response:

There's no real reason to use an environment variable at all; a simply command line argument would suffice.

GIT_PASSWORD=$1

python - "$GIT_PASSWORD" << EOF 
import sys
print(sys.argv[1])                                               
EOF

echo "Back to bash"
  • Related