Home > Net >  Declaring a bash function inside a docker image
Declaring a bash function inside a docker image

Time:07-06

Using a Dockerfile to build an image which I later use to run a container used to cross-compile a binary for a target platform. This container is used for development, so I work hours inside this container. The "make" command is building the binary properly.

For debug purposes, I need the output of the make command being saved to a logfile transparently. I solved this adding a bash "make" function to my Dockefile:

RUN echo 'make() { DATE=$(date " %Y%m%d-%H%M%S"); LOGNAME=build_$DATE.log; $(which make) "$@" 2>&1 | tee /tmp/$LOGNAME; }' >> ~/.bashrc

As you can see, I modify the .bashrc. Function "make" is declared when I run into the container. Inside the container, whenever I run "make" command, the logs are always saved into /tmp/$LOGNAME, as expected.

I wonder if there is a more convenient / clean way to define a bash function in the running shell without defining this RUN command in the Dockefile.

CodePudding user response:

I will

  • Externalize your Bash function in a dedicated file make.sh aside your Dockerfile:
#!/usr/bin/env bash

make() {
   DATE=$(date " %Y%m%d-%H%M%S")
   LOGNAME=build_$DATE.log
   $(which make) "$@" 2>&1 | tee /tmp/$LOGNAME
}
  • Add a Dockerfile instruction to copy the make.sh script in the container:
COPY make.sh ~/make.sh
  • Add a Dockerfile instruction to source the make.sh script in the .bashrc:
RUN echo "source ~/make.sh" >> .bashrc

CodePudding user response:

One alternative is to fully control your .bashrc file from within the host and copy it to the image with a Dockerfile COPY instruction.

  • Related