skip to Main Content

In my dockerized container I am unable to replace a variable using ‘sed’.

These are my files:

myfile.sql

CREATE TABLE IF NOT EXISTS ${PG_TABLE}(...)

myscript.sh

#!/bin/sh
echo "variable1=${1}"
echo "variable2=${2}"
sed  -i "s/${$1}/$2/g" myfile.sql

run command

myscript.sh PG_TABLE "mytablename"

Actual:

  • echo variable1=PG_TABLE
  • echo variable2=mytablename
  • REPLACEMENT:
    CREATE TABLE IF NOT EXISTS (…)

Expected:

  • echo variable1=PG_TABLE
  • echo variable2=mytablename
  • REPLACEMENT
    CREATE TABLE IF NOT EXISTS mytablename(…)

This is supposed to replace the placeholder with my variable ‘mytablename’, but it just replaces it with empty string.

Maybe its because of my container alpine version.
This is my os.

my docker build operating system

cat /etc/os-release
  • PRETTY_NAME="Debian GNU/Linux 12 (bookworm)"
  • NAME="Debian GNU/Linux"
  • VERSION_ID="12"
  • VERSION="12 (bookworm)"
  • VERSION_CODENAME=bookworm
  • ID=debian

2

Answers


  1. Chosen as BEST ANSWER

    ok I made a mistake. The reason it didn't work is because I was expecting the arg to exist in my docker-compose file and it wasn't. Therefore the replacement was empty "". Adding in that arg

    docker-compose.yml

    ...
        build:
          context: .
          args:
           - PG_DB=${PG_DB}
           - PG_TABLE=${PG_TABLE} # Needed to pass variable to Dockerfile during 
    

    Dockerfile

    # ...
    FROM postgres
    ARG PG_DB #  Need to recieve arg
    ARG PG_TABLE
    
    ADD seed.sql /docker-entrypoint-initdb.d/seed.sql
    
    COPY script.sh .
    RUN chmod +x script.sh
    
    # Need to pass arg to script
    RUN ./script.sh PG_DB "${PG_DB}" PG_TABLE "${PG_TABLE}" 
    

  2. Issue is with sed placeholder.

    Use ${${1}} to match the placeholder in the myfile.sql

    Here’s the working solution, where running the container shows correct replacement.

    myscript.sh

    #!/bin/sh
    echo "variable1=${1}"
    echo "variable2=${2}"
    echo "Running sed command..."
    echo "sed -i "s/\${${1}}/${2}/g" /app/myfile.sql"
    sed -i "s/${${1}}/${2}/g" /app/myfile.sql
    cat /app/myfile.sql
    

    myfile.sql

    CREATE TABLE IF NOT EXISTS ${PG_TABLE}(...);
    

    Dockerfile

    FROM debian:bookworm
    
    RUN apt-get update && apt-get install -y sed
    
    COPY myfile.sql /app/myfile.sql
    COPY myscript.sh /app/myscript.sh
    
    WORKDIR /app
    
    RUN chmod +x myscript.sh
    
    CMD ["./myscript.sh", "PG_TABLE", "mytablename"]
    
    • docker build -t sed-replacement .
    • docker run –rm sed-replacement

    OUTPUT

    variable1=PG_TABLE
    variable2=mytablename
    Running sed command...
    sed -i "s/${PG_TABLE}/mytablename/g" /app/myfile.sql
    CREATE TABLE IF NOT EXISTS mytablename(...);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search