Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Querying Git status with Subprocess throws Error under Linux

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[[ -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?

>Solution :

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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading