bashdockerdocker-composesed

how to insert a new service into docker-compose.yml using sed


I want to add a new service into docker-compose.yml with bash. this is how it looks:

#!/bin/bash

# Check if the file exists
if [ ! -f "docker-compose.yml" ]; then
  echo "Error: docker-compose.yml file not found"
  exit 1
fi

#insert new service into docker-compose.yml
new_service=$(cat << SERVICE
# New service section
new_service:
  image: some_image
  ports:
    - "8080:80"
SERVICE
)

# Check if the service already exists
if grep -q "^new_service:" docker-compose.yml; then
  echo "Service 'new_service' exists in docker-compose.yml"
else
  echo "Service 'new_service' does not exist in docker-compose.yml, inserting"
  sed -i "/# New service section/a ${new_service}" docker-compose.yml
  echo "Service section added to docker-compose.yml"
fi

this looks straight forward but throws:

Service 'new_service' does not exist in docker-compose.yml, inserting
sed: -e expression #1, char 49: extra characters after command
Service section added to docker-compose.yml

I created a very basic docker-compose.yml file but sed still complains, so maybe there is a better approach?

version: "3.9"
services:
  redis:
    image: "redis:alpine"
# New service section

Solution

  • Alternatively, you can try using awk For example:

    #!/bin/bash
    
    old_dc=$(cat docker-compose.yml)
    
    new_service=$(cat << SERVICE
      new_service:
        image: some_image
        ports:
          - "8080:80"
    SERVICE
    )
    
    new_dc=$(echo "$old_dc" | awk -v var="$new_service" '/services:/ {p=1} {print} p && /services:/ {print var; p=0}')
    
    echo "$new_dc" > docker-compose.yml