0

Regarding this post How to include python script inside a bash script , I get used to work with python HereDoc. However, I want to include that python HereDoc inside a for loop, and so, it needs to be idented but it does not seem to be recognized by Visual Studio starting in blue color from the first HereDoc. Also python is blank because it is not written yet, but I wanna know if it is possible to call for a HereDoc inside a Bash Shell Loop.

datarange=$(LC_ALL="POSIX" seq -f %.15g 0.5 0.25 5.5 | sed '/\./!s/$/.0/') 
for i in $datarange
do
    cp -r MovableFiles/mode-1 D$i
    cp -r MovableFiles/mode-4 D$i
    echo -n CWD:; /bin/pwd 
    cd $PBS_O_WORKDIR
    echo -n CWD:; /bin/pwd 
    cd D$i
    cd mode-1
    echo -n CWD:; /bin/pwd 
    # changes input files for mode-1
    python3 - << HERE
HERE

cd mode-4
echo -n CWD:; /bin/pwd 
# changes input files for mode-4
python3 - &lt;&lt; HERE




HERE

done

What I want to do is a loop over the input files on "MovableFiles", moving them to directories D$i and changing a specific line on the fly (regarding the $i number), but I tend to do the text-change in Python3 so that's why I need a HereDoc or any other way to use Python3 inside a loop.

PARCB
  • 1

1 Answers1

3

You can declare each block of Python code with local column-1 indentation within its own Bash function.

emitPy_Mode_4 () { cat <<'EOF'
Your python source
    goes here with
        any indentation you like
Just fine
EOF
}

You can invoke it within the Bash loop through stdin like:

emitPy_Mode_4 | python3 -

or as a Here String like:

python3 - <<<"$( emitPy_Mode_4 )"

A Here Document is either completely quoted, or completely unquoted (depending on whether the start marker in <<EOF is quoted). Unquoted, it will be subject to shell expansions, and vulnerable to characters that mean something else in the text being passed, unless each occurrence is itself escaped.

If the HereDoc is wrapped in a function, it can be split into sections with different quoting, to control expansion. Required variables can be passed into the function:

emitPy_Mode_4 () {  #.. Takes one filename argument.
cat <<'EOF'    #.. Preamble
Your python source
EOF
cat <<EOF      #.. Inject variable.
    myPathName = '${1}'
EOF
cat <<'EOF'    #.. Remainder.
    goes here with
        any indentation you like
Just fine
EOF
}

IIRC, the unquoted section can include any shell construct, like a process expansion, which can call any other function, or external command, to inject text into the HereDoc.

Paul_Pedant
  • 8,679