Difficulty Detecting OS Distribution (Debian or Alpine) in Dockerfile

I am working on a Dockerfile where I need to determine the OS distribution of the base image to perform different actions based on whether it’s Debian or Alpine Linux. I’ve tried using /etc/os-release, but I’m encountering some issues.

Here’s the simplified Dockerfile:

# Use a base image of your choice (e.g., debian, alpine, or other)
FROM debian:bullseye

# Check the contents of /etc/os-release
RUN cat /etc/os-release

# Detect the base image distribution
RUN source /etc/os-release && \
    if [[ $ID == "debian" ]]; then \
        echo "This is a Debian-based image"; \
    elif [[ $ID == "alpine" ]]; then \
        echo "This is an Alpine-based image"; \
    else \
        echo "This is another Linux distribution"; \
    fi

The issue I’m facing is that the conditional statements based on $ID are not working as expected. When I run this Dockerfile, it often falls into the “This is another Linux distribution” branch, even when the base image is clearly Debian or Alpine.

I’ve checked the /etc/os-release file, and it appears to have the correct information. However, the conditional checks seem unreliable.

Is there a more robust and reliable way to identify the base image’s distribution within a Dockerfile?

I appreciate any insights or solutions to help me determine the OS distribution correctly in the Dockerfile.

Maybe a hacky workaround:

ID=$( grep "^ID=" /etc/os-release | awk -F= '{print $2}' )