0

I'm trying to transfer a variable in a bash-script to an embedded python-function. A minimal example of the script I'm using is given below:

#!/bin/bash

function python_print() {
PYTHON_ARG="$1" python - <<END
import os
p = str(os.environ['PYTHON_ARG'])
print('The Variable is ' + p)
END
}

DIRIN=$1
FULLPATH=$ realpath $OUTFILE
python_print $FULLPATH

Running the script gives me: "The variable is "; so it seems the argument FULLPATH is not transfered to the function. The strange thing is, the code works if "$FULLPATH" is replaced either with "$1", "$DIRIN" or any hardcoded string. Where is my mistake? I'm grateful for any advice!

3
  • 1
    But where is OUTFILE ever defined? Commented Jan 22, 2018 at 14:59
  • 3
    If instead of python_print $FULLPATH you did echo $FULLPATH does it print the value you expect? I suspect the line above is meant to be FULLPATH=$(realpath $OUTFILE) Commented Jan 22, 2018 at 15:01
  • @Bailey Parker: My mistake, I tried to post a minimal example of my original script, so I accidently deleted the line "OUTFILE=$2". Commented Jan 22, 2018 at 15:51

2 Answers 2

1

The problem is not in python_print function (note that function keyword is redundant with ()). but in FULLPATH assignment and function call

correct syntax

FULLPATH=$(realpath "$OUTFILE")
python_print "$FULLPATH"
  • no space between = and value in assignment
  • double quotes around variable expansion in function call
  • expansion must be double quoted except
    • if $ appears just after = in assignment
    • conditions between double brackets [[ ]]

note that

FULLPATH=$ realpath $OUTFILE

is not affecting FULLPATH in current shell process environment, it just sets FULLPATH to $ to realpath execution process environment also output is not captured.

Sign up to request clarification or add additional context in comments.

Comments

0

Just either:

  • export your bash variable so it is available in os.environ
  • or use positional parameters and read it from sys.argv

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.