+ tree
.
├── compose.yml
└── my-script
+ cat my-script
docker compose run --rm test
ec=$?
echo Exit code: $ec
if [ $ec -eq 0 ]; then
echo No errors found
fi
+ cat compose.yml
services:
test:
image: phpdoc/phpdoc:3
user: "${UID}:${GID}"
+ sh -u my-script
WARN[0000] The "UID" variable is not set. Defaulting to a blank string.
WARN[0000] The "GID" variable is not set. Defaulting to a blank string.
blah blah blah
Exit code: 0
No errors found
Let’s look at things in more detail
WARN[0000] The "UID" variable is not set. Defaulting to a blank string.
WARN[0000] The "GID" variable is not set. Defaulting to a blank string.
This will produce a none zero exit code (1) if either are unset.
#!/bin/sh
set -eu
# Manually enforce presence of UID and GID
: "${UID:?Environment variable UID is not set}"
: "${GID:?Environment variable GID is not set}"
docker compose run --rm test
ec=$?
echo "Exit code: $ec"
if [ "$ec" -eq 0 ]; then
echo "No errors found"
fi
e: This option causes the script to exit immediately if any command fails (this returns a non-zero exit code).
u: This option treats unset variables as an error when performing parameter expansion. The script will exit if it tries to use an undefined variable.
: "${UID:?Environment variable UID is not set}"
This is a form of parameter expansion.
If the environment variable UID is not set or is null, the script will print the message “Environment variable UID is not set” to standard error and exit with a non-zero status (due to set -u and set -e).
If UIDis set, the : (colon) command (which is a built-in no-op that successfully does nothing) is executed, and the script continues.
: "${GID:?Environment variable GID is not set}"
This works exactly like the UID check above but for the GID environment variable. If GID is not set, the script prints the specified error and exits with a non-zero status.
docker compose run --rm test
This command attempts to run a service named test defined in your docker-compose.yml file.
If this command fails for any reason, it will return a non-zero exit code. Reasons for failure could include:
The docker-compose.yml file is missing or misconfigured.
The service test is not defined.
The Docker image for the test service cannot be built or pulled.
The container itself exits with a non-zero status during its execution.
Because set -e is active, if docker compose run fails, the script will immediately exit at this point with that non-zero exit code.
ec=$?
This line captures the exit code of the immediately preceding command (docker compose run --rm test) and stores it in the variable ec.
echo "Exit code: $ec"
This line will print the captured exit code.
if [ "$ec" -eq 0 ]; then echo "No errors found"; fi
This conditional statement checks if the exit code stored in ec is equal to 0.
If ec is not 0 (meaning an error occurred in docker compose run), the message “No errors found” will not be printed.