Home > Blockchain >  Why does my shell script does not recognize Python scripts result?
Why does my shell script does not recognize Python scripts result?

Time:06-15

I have a shell script that calls a python script. The python script returns a variable "Found" back to the main shell. While I am able to display the result variable in main shell, the variable is not being recognized in conditions.

#!/bin/bash
PythonScript="C:\Users\arun\Test.py"
Pythonresult="$(py "${PythonScript}")"
Varuableresult="Found"

echo "Display both the results here..."

echo "Variable result is..." $Varuableresult
if [ "$Varuableresult" = 'Found' ]; then
    echo "Variable result in condition working"
fi

echo "Python result is..." $Pythonresult
if [ "$Pythonresult" = 'Found' ]; then
    echo "Python result in condition is working"
fi

The python script (Yes, it's just one line):

print("Found")

The output:

$ sh 'C:\Users\myusername\Documents\Value_Adds\FTP_Filecheck\Test.sh'
Display both the results here...
Variable result is... Found
Variable result in condition working
Python result is... Found

Why does the variable is not recognized in the condition?

I'm executing the shell script in Cygwin

CodePudding user response:

It's likely, since you're on Windows, that your Python script's output has DOS newlines (CRLF instead of UNIX-standard LF), so your string is really $'Found\r' instead of 'Found', but they look the exact same to echo. Trace logs with set -x will make this obvious. ($'\r' is how bash writes the carriage return character, which when printed sends the cursor back to the far left side of the current line but has no other visible effect).

You can use Pythonresult=${Pythonresult%$'\r'} to strip that character off -- though it's not guaranteed to work reliably unless you change your script from being a sh script to a bash script ($'...' is originally a ksh extension picked up by bash and zsh, but is not a feature found in the POSIX sh standard, so /bin/sh doesn't guarantee support for it).

As another option, if you use a Python installed with cygwin instead of using a native Windows Python interpreter, that might stop those unwanted characters from showing up in the first place.

  • Related