• Linux
  • FreeBSD
  • Networking
  • Python
  • AWS
  • WebDev
  • About Us

Error: /bin/sh: Syntax error: unexpected in Python3

Written by
Python Leave a Comment

If you are wrapping shell commands with Python modules you might see this error a number of times . This usually happens when you grep some output from a command and assign it to a variable and then you will need to use that variable in another command . So there will be a new line character that comes with your greped output on the first variable . So when executing this from another command the cli sees the new line as “enter” and sees the two seperate lines as two different commands .

The solution is to strip the string at the end to make it ‘clean’

For eg : If I need to grep the gateway of an interface using netstat command , the gway.read() is my grepped IP but then I need to run the .strip() at the end to clear the new line character . You can then use this str(gway) with other commands on the same script .

command = "netstat -r4n | grep igb1 | ......."
gw = os.popen(command)
gway = gw.read()
gway = gway.strip()

© Copyright 2020.TechieNix. All Rights Reserved.