简体   繁体   中英

Why does my shell script does not recognize Python scripts result?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM