hmontoliu

~
~
:wq

Saturday 27 June 2015

Passing STDIN or positional arguments to python code enbedded in bash script (here-documents)

spanish version - all english posts

This is a short post about bash's here-documents and python embedded scripts. Very useful to write quick and dirty scripts.

The issue here is to demonstrate how to pass either positional arguments or stdin input (pipe) to python code inside a bash's here-document block of code

Proposal, write a bash script or function that accepts either pipe input or positional parameters and pass them to a python block of code within the bash script.

First approach: ever wonder how to pass bash positional args to inside python here document? Here is the code:

#! /bin/bash

[... bash stuff ...]

# our python block
python - $@ << EOF
import sys
print sys.argv[:]
EOF

[... more bash stuff ...]

this is how it works:

bash firstapproach.sh one two
['-', 'one', 'two']

Let's go ahead... What if you want to accept ether standard input or positional args? this is IMHO a good approach to the problem (using a function to make the code clearer):

#! /bin/bash

[... bash stuff ...]

# the function which passes to our python here-document either
# positional args or STDIN input
# pipe input is only used if no positional args are present:
myfunct () {
[[ $# > 0 ]] && ARGS=$@ || read ARGS
python - $ARGS << EOF
import sys
print sys.argv[:]
exit
EOF
}

[... more bash stuff ...]

And here is the resulting output of both the STDIN and the positional args:

~$ echo hola amigos | myfunct
['-', 'hola', 'amigos']

~$ myfunct hasta luego
['-', 'hasta', 'luego']

HTH