0

What is the best way to find out in which environment the bash script is running (on the host machine or in a docker image)?

My bash script:

#!/bin/bash
function PKG_ABSENT { return `which "$1" 2>/dev/null | grep -cm1 "$1"`; }

if ! PKG_ABSENT "docker"; then
    # Docker package is installed
    echo "running in the host machine"
else
    # Docker package is not installed
    echo "running in a Docker image"
fi

Any Ideas?

Alexander Yukal
  • 173
  • 1
  • 9
  • 1
    The docker image may have docker installed. Nothing prevents you from `docker run docker`. Even you can run docker inside docker `docker run -ti --rm -v /var/run/docker.sock:/var/run/docker.sock docker docker run -ti --rm alpine` – KamilCuk Oct 30 '18 at 11:08
  • 1
    As an aside, `type` is the portable POSIX replacement for the non-portable `which` which exists in many mutually incompatible and variously buggy versions. It sets its exit code properly so there is no need to `grep` anything or indeed wrap it in a function at all. – tripleee Oct 30 '18 at 11:12

0 Answers0