Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

The following is the python one-liner I want to run as part of my bash script

python -c "from xml.dom.minidom import parse;dom = parse('/path/to/pom.xml');print [n.firstChild.data for n in dom.childNodes[0].childNodes if n.firstChild and n.tagName == 'version']"

(pom.xml is a maven POM xml file)

I want to have the result of the command be assigned to variable MVN_VER

This is my base script:

WS="/path/to"
PY_GET_MVN_VERS="from xml.dom.minidom import parse;dom = parse(\'${WS}/pom.xml\')\;print [n.firstChild.data for n in dom.childNodes[0].childNodes if n.firstChild and n.tagName == \'version\']"

funcion test_mvn {

        MVN_VER=`python -c \"${PY_GET_MVN_VERS}\"`
        echo ${MVN_VERS}
}

test_mvn

However it fails to run. If I run the script with +x option, it is what I see:

++ python -c '"from' xml.dom.minidom import 'parse;dom' = 'parse(\'\''/path/to/pom.xml\'\'')\;print' '[n.firstChild.data' for n in 'dom.childNodes[0].childNodes' if n.firstChild and n.tagName == '\'\''version\'\'']"'
  File "<string>", line 1
    "from

I think it has something to do with escaping the python code. How can I escape it properly?

share|improve this question
up vote 4 down vote accepted

There is no need for escaping or moving the argument to its own variable.

But, keeping it mostly the same, the following works for me:

#!/usr/bin/env bash
WS="/Users/danielbeck/Desktop"
PY_GET_MVN_VERS="from xml.dom.minidom import parse;dom = parse('${WS}/pom.xml');print [n.firstChild.data for n in dom.childNodes[0].childNodes if n.firstChild and n.tagName == 'version']"
function test_mvn {
        MVN_VER=$( python -c "${PY_GET_MVN_VERS}" )
        echo ${MVN_VER}
}
test_mvn

/Users/danielbeck/Desktop/pom.xml is the example minimal POM from the Maven docs:

<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany.app</groupId>
  <artifactId>my-app</artifactId>
  <version>1</version>
</project>

Output:

[u'1']

Please throw away your code and just use mine (after adjusting WS) instead of adjusting yours until it works. You have quite a few syntax errors in there.

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .