Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to split a environment variable based on delimiter in Docker

I am trying to split the following string into array on delimiter

str="We;Welcome;You;On;Javatpoint"

I manage to find a solution in bash that is

#!/bin/bash  
#Example for bash split string by another string  
  
str="We;Welcome;You;On;Javatpoint"  
delimiter=";"  
s=$str$delimiter  
array=();  
while [[ $s ]];  
do  
array+=( "${s%%"$delimiter"*}" );  
s=${s#*"$delimiter"};  
done;  
declare -p array

Results in

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

array=([0]="We" [1]="Welcome" [2]="You" [3]="On" [4]="Javatpoint")

I need to split the string into an array inside Dockerfile.

DOCKERFILE:

> FROM python:3.7-slim
> 
> ENV IN="We;Welcome;You;On;Javatpoint"

>Solution :

Just let bash do the splitting.

IFS=';' read -r -a array <<<"str"

or similar with readarray for multiline variables.

inside Dockerfile

If you want to use bash features make sure first that you are runnig Bash. RUN commands in dockerfile by default sexecute /bin/sh (see dockerfile reference documentation) which may not be Bash and may not support Bash arrays.

In this specific case, to be /bin/sh compatible, replace ; for a newline (tr) and read it as a newline separated stream or use word-splitting if there are no other whitespaces. See https://mywiki.wooledge.org/BashFAQ/001

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading