Run python oneliner in bash script
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?
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.