0

Let's say I want to create a file with the following content:

Line1
Line2
Line3
Line4

You'd instantly think in something like:

for i in 1 to 4:
 print "Line"+ i

I have done this before with Vagrant. I did a Nginx configuration like this:

worker_processes  1;
events {
   worker_connections 1024;
}
http {
    upstream servers {
    <% @ips.each do |ip| %>
       <%= 'server ' + ip + ' ;'%>  
    <% end %>
    }
    server {
        listen 8080;
        location / {
              proxy_pass http://servers;
        }
    }
}

But I'm not the know-it-all guy when it comes to technologies, so I'm not sure if this syntax is a Vagrant thing only because that is clearly Ruby.

My questions are:

  • Is there any way to do the same in Docker? I mean native Docker.
  • Is there any techonolgy independent from the virtualization means that can do the same without being too "Linuxish". I mean, almost Ruby, Java or Python code.
  • Is there any techonolgy that has the Linux feeling?

Feel free to answer any of the questions.

  • 2
    In box linux and windows any command that generates output can be used to create "Dynamic file content", you simply need to redirect output of the commands to a file. In both bash and batch you could write a for loop that simply echos the content you want and redirect the output to a file. – Centimane May 2 '17 at 14:06
3

Using a shell script (most "native language" in this forum):

#!/bin/sh

i=1

while [ "$i" -le 4 ]; do
   printf "line%d\n" "$i"
   i="$(( i + 1 ))"
done >output_file

Or with bash or ksh93:

#!/bin/bash

printf "line%d\n" {1..4} >output_file

Alternatively,

#!/bin/bash

for ((i = 1; i <= 4; ++i)); do
  printf "line%d" "$i"
done >output_file
  • Would this generate another file? The rendered template? – AFP_555 May 2 '17 at 14:04
  • @AFP_555 The above snippets of shell code will generate text files called output_file. The purpose of the question is unclear. Do you need to generate this under any particular circumstances or in any particular format? This is one "technology" that Unix offers to generate a simple text file with an incrementing counter. You could probably run this in a script called from Nginx inside a Docker container if you wished. (just don't ask me how since I've not worked with Docker nor Nginx). – Kusalananda May 2 '17 at 14:11
  • 1
    FYI, the {1..4} syntax comes from zsh. You'd only use expr for non-POSIX sh. But those sh would typically not support $(...) either. Only exception would be very old ash-based shells that supported $(...) but not $((...)). – Stéphane Chazelas May 2 '17 at 14:16
  • See also seq -f line%g 4 or those loops written in awk or bc/dc to avoid running so many commands. – Stéphane Chazelas May 2 '17 at 14:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.