Preferred way of detecting snap confinement

That question came up when I contributed a change to an upstream project that needed a specific code path when confined as a snap (I understand this should be avoided where possible, but it’s not always possible). I did something like that:

if (std::getenv("SNAP") != nullptr) {
    // snap-specific code path
}

Is there a better way?

1 Like

This is a tricky test as whatever this is might be called by another snap (in the case of classic) and it will have the SNAP variable exported which would affect the check if the called program was not a snap.

For the record, this already happened with a program snapcraft used. The deb build had the SNAP check and caused havoc when called from the snapcraft snap. In snapcraft we resort to SNAP_NAME == 'snapcraft' but we have total end to end control here (this ties the upstream to a specific snap name)

1 Like