pythonlinuxshellredhat

Runing shell script with python temporary environment variables


I am trying to find a way to run a python script with temporary env variables underground. I am using the following script to illustrate my approach, but it does not work.

example.py

import os 
import sys 
name = os.environ.get('CONF_NAME') + '.yaml'

print('Execution of the file {} '.format(name))

example.sh

OUTPATH="/home/user1/samples"
ERRPATH="/home/user1/samples"
PREFIX="CONF_NAME=\"$1\""
EXECUTION_COMMAND="python"
FILE_TO_EXECUTE="example.py"

echo saving stderr to ${ERRPATH}
echo saving stdout to ${OUTPATH}

${PREFIX} nohup ${EXECUTION_COMMAND} ${FILE_TO_EXECUTE} > ${OUTPATH}/example_output.out 2> ${ERRPATH}/example_error.out &

But I get error of the form

example.sh: 10: CONF_NAME="conf_file_abc": not found

when I run the command

sh example_two.sh conf_file_abc

I would really appreciate your help to find a solution


Solution

  • Bash is not a macro langauge. What is the result of expansion is not what you type.

    If you type CONF_NAME="$1" Bash parses quotes, expands $1, and assigns variable.

    If you type ${PREFIX}, then the result of expansion is not parsed or expanded. It is the result of expansion, and that result is used. The result of expansion is CONF_NAME="<first arg>" literally including " quotes, as the " quotes are inmluded inside the PREFIX variable.

    Research a shell introduction. See introductions to quoting and shell expansions. https://mywiki.wooledge.org/BashFAQ/050 is somewhat relevant. Use set -x to debug shell scripts.

    Just do:

    export CONF_NAME="$1"
    

    Or if you really want:

    CONF_NAME="$1"
    ...
    CONF_NAME="$CONF_NAME" nohup ...
    

    To store multiple environment variables for later use, you can use env command and Bash array.

    envs=(
      CONF_NAME="$1"
    )
    env "${envs[@]]" nohup ....