2

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?

3
  • Have you got #!/usr/bin/python at the start of the Python script? The path needs to be the actual path on your local system. Commented Nov 18, 2020 at 13:29
  • Hi @RamanSailopal , yes I've python path present in my script: #!/usr/bin/env python3 Commented Nov 18, 2020 at 13:32
  • The result of your python command contains quotes, which most likely causes the error. I recommend avoiding the whole eval business, as that can cause you a lot of grief if you are new to bash. If you goal is to return some string from a function you should consider using the sub-process approach or simply assigning to a global variable, as those are generally easier to work. Commented Nov 18, 2020 at 14:40

1 Answer 1

1

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')]"
Sign up to request clarification or add additional context in comments.

1 Comment

printf -v "$1" "%s" "$(/home/centos/pentaho2.py)" is also an option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.