Search code examples
dockerdockerfilesh

How do I call a function from a shell script in Docker?


I'm trying to call a function runaudit inside of of my docker container.

The shell script, which contains the runaudit function, is copied inside of the image and the BASH_ENV environment variable is set to point to /etc/audittools/audit.sh

My question is, how do run this runaudit function inside of my container?

I tried to run it inside the container but I get the following message.

/ # runaudit
/bin/sh: runaudit: not found

The ENV output is showing me that the environment variable has been set.

Herewith the Dockerfile and small shell function.

NOTE : The real function is much larger and I need to keep it maintained inside of it's own file.

I appreciate any advice or help with this.

Dockerfile

FROM alpine:3.10

MAINTAINER acme

ARG VERSION=0.3.0

RUN apk add --no-cache curl tar gettext libintl

RUN envsubst --version

RUN mkdir -p /etc/audittools

COPY audit.sh /etc/audittools

RUN chmod a+x /etc/audittools/audit.sh

ENV BASH_ENV "/etc/audittools/audit.sh"

Shell Script - audit.sh

#!/usr/bin/env sh
function runaudit() {
    echo "Hello World"
}

Run the function

docker run -it test /bin/sh runaudit

Solution

  • Change this to be an ordinary shell script; in generic programming terms, make it a "program" and not a "function".

    Remember that docker run starts a new container with a clean environment, runs whatever its main program is, and then exits. Also remember that the difference between a shell script and a shell function is that a function runs in the context of its calling shell and can change environment variables and other settings, whereas a shell script runs in a new shell environment; but since in a docker run context the parent shell environment is about to get torn down, it doesn't matter.

    So I'd change the shell script to

    #!/bin/bash
    # ^^^ use the standard shell location
    # vvv remove the function wrapper
    echo "Hello World"
    

    and then change the Dockerfile to run it on startup

    ...
    COPY audit.sh /etc/audittools
    RUN chmod a+x /etc/audittools/audit.sh
    CMD ["/etc/audittools/audit.sh"]