Home > Net >  Querying Git status with Subprocess throws Error under Linux
Querying Git status with Subprocess throws Error under Linux

Time:05-06

I want to query the status of the git repo using python. I am using:

subprocess.check_output("[[ -z $(git status -s) ]] && echo 'clean'", shell=True).strip()

This works fine on MacOS. However, on Ubuntu Linux I get an error message:

{CalledProcessError}Command '[[ -z $(git status -s) ]] && echo 'clean'' returned non-zero exit status 127.

I went into the same folder and manually ran

[[ -z $(git status -s) ]] && echo 'clean'

and it works fine.

I further ran other commands like

subprocess.check_output("ls", shell=True).strip()

and that also works fine.

What is going wrong here?

CodePudding user response:

When you set shell=True, subprocess executes your command using /bin/sh. On Ubuntu, /bin/sh is not Bash, and you are using Bash-specific syntax ([[...]]). You could explicitly call out to bash instead:

subprocess.check_output(["/bin/bash", "-c", "[[ -z $(git status -s) ]] && echo 'clean'"]).strip()

But it's not clear why you're bothering with a shell script here: just run git status -s with Python, and handle the result yourself:

out = subprocess.run(['git', 'status', '-s'], stdout=subprocess.PIPE)
if not out.stdout:
  print("clean")
  • Related