Bash script - Command not found error on consuming Python output

Viewed 92

I've a bash script, which calls a python script. Python script returns me an object, which I then assign to a variable in bash and have to return.

I am getting command not found when I try to eval the output of the python script. Bash is treating it as a command instead of a value.

Below is the code:

function myfunc()
{
    local  __resultvar=$1
    local  myresult=$(/home/centos/pentaho2.py)
    eval $__resultvar="'$myresult'"
}

myfunc result
echo $result

My python command returns me a value like this:

[('quatre vingt douze ave des champs-élysées', 'road')]

After executing the script, I see this error:

./pentaho2.sh: line 5: vingt: command not found

Could someone help me understand what am I missing here?

1 Answers

If your bash version is 4.3 or greater, using a nameref in your function allows you to avoid eval and the inherent quoting problems

myfunc() {
    local -n __resultvar=$1
    __resultvar=$(/home/centos/pentaho2.py)
}

myfunc result
echo "$result"

To see the error in action, use set -x:

myresult="[('quatre vingt douze ave des champs-élysées', 'road')]"
set -x
eval result="'$myresult'"

output

+ eval 'result='\''[('\''quatre vingt douze ave des champs-élysées'\'', '\''road'\'')]'\'''
++ result='[(quatre'
++ vingt douze ave des 'champs-élysées, road)]'

A quoting problem indeed.


An alternative is to use declare instead of eval

$ __resultvar=result
$ declare "$__resultvar=$myresult"
$ declare -p result
declare -- result="[('quatre vingt douze ave des champs-élysées', 'road')]"
Related