cli icon indicating copy to clipboard operation
cli copied to clipboard

docker ps -f should return nonzero exit status for no matches

Open damobrisbane opened this issue 3 months ago • 1 comments

Description

As per vdemeester comment, re-opening https://github.com/moby/moby/issues/35057.

Reason to close was command will return zero even when "docker ps" returns no containers.

If instead docker ps returns ie 1 or not zero when container is not running, it then enables better integration with other tooling:

# Conventional Exit Code Use - ls command on folder exists, not-exists
 
if [[ $( ls /tmp 2>/dev/null ) ]]; then echo "folder exists"; else echo "folder does not exist"; fi

folder exists
 
if [[ $( ls /tmpXX 2>/dev/null ) ]]; then echo "folder exists"; else echo "folder does not exist"; fi

folder does not exist

# Docker ps - Less Useful Zero Exit Code

if [[ $( docker ps --filter label=runningimage=no 2>/dev/null ) ]]; then echo "container is running"; else echo "container is not running"; fi

container is running

??? WHY
 
eg, docker ps - no containers are running
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
.... 


Another closer example, "pgrep" - listing processes by process matching, clearly explains rationale:

...
       -c, --count
              Suppress  normal  output;  instead print a count of matching processes.  When count does not match anything, e.g. returns zero, the command will return
              non-zero value. Note that for pkill and pidwait, the count is the number of matching processes, not the processes that were  successfully  signaled  or
              waited for.


damobrisbane avatar Nov 09 '25 19:11 damobrisbane

Thanks @damobrisbane for raising this. I agree that when docker ps is run with filters and no containers match, returning a non-zero exit status would be more useful for scripting and CI scenarios. Right now it’s hard to distinguish “no matches” from a successful result in automation.

I’m happy to take a look at this. My plan would be to reproduce the current behavior, update the ps command so the filtered/no-results case returns a non-zero exit code, and add tests to cover it. I’ll keep the change limited to the filtered case so existing docker ps usage isn’t affected.

Let me know if there are any concerns with that approach.

ali63yavari avatar Dec 16 '25 08:12 ali63yavari