2

I have been trying to write an executable script which creates files containing multiple variables.

Here, x varies from 1 to 25, z from 5 to 7 at steps of 0.1, whilst y and w are constants. Hence, for each value of x, there must be 21 files. I have tried the below, however I can't get my head around how such a nested for loop should work.

mkdir dir
for ((i=1;i<=25;i++)); do
    printf 'x=%s\ny=4\n' "$i"
    for ((j=5;j<=7;j=j+0.1));do
        printf 'z=%s\nw=4\n' "$j" > dir/diles_$i_$j.txt
done

Also, how can I make this executable? I am working on Ubuntu.

Eliah Kagan
  • 119,640
Druni
  • 21

1 Answers1

1

Here is your solution :

#! /bin/bash

mkdir dir
for ((i=1;i<=25;i++)); do
    printf 'x=%s\ny=4\n' "$i"
    for ((j=50;j<=70;j++));do
        t=$(bc <<< "scale=1; $j/10")
        printf 'z=%s.1f\nw=4\n' "$t" > dir/diles_$i\_$t.txt
    done
done

Explanation :

  • Bash works only with integer, so you can't do your loop with a float / decimal (you see that I just use a division by 10 below)
  • We use bc command, which convert integers operation (a division for example) in order to get float; scale operator show how many decimal we want to have (here, 1 is suffisant in order to not have many 0, like bc -l do)
  • we need to add a \\ in the filename because it didn't take care of the i to name files ifnot

Also, I pointed that your 1st printf command just print result like that in the terminal, probably you would add them inside each file (instead of terminal display), so you must use the code below in this case :

#! /bin/bash

mkdir dir
for ((i=1;i<=25;i++)); do
    for ((j=50;j<=70;j++));do
        t=$(bc <<< "scale=1; $j/10")    
        printf 'x=%s\ny=4\n' "$i" > dir/diles_$i\_$t.txt
        printf 'z=%s.1f\nw=4\n' "$t" >> dir/diles_$i\_$t.txt
    done
done

NB : the >> operator or the 2nd printf command is important here (1st printf didn't care, depends only if you want to take care of previous data - >> -, or not - >), because if you use just a > operand, you would erase all previous data (so output of the 1st printf would be removed)

Sources :

damadam
  • 2,873