0

I am trying to write a bash script which will fill a file in a for loop, such that if I run the script with argument 3 it will create the file with 3 lines.

This is the script that I came up with. But it creates the file with only one line.

#!/bin/bash
for i in $1
do
cat > $PWD/http_file$1.csv <<EOF
host_$i,8080,app_$i,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
EOF
cat $PWD/http_file$1.csv
done
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
yunger
  • 27
  • 4

2 Answers2

1

for i in 3: bash sees this as looping over all space-delimited options after in. In this case, there is only one element, so the loop only runs once.

You can generate a list of numbers via seq:

echo $(seq 1 3)
> 1 2 3

TL;DR: Use for i in $(seq 1 $1)

jeremysprofile
  • 10,028
  • 4
  • 33
  • 53
  • Alternatively you could use this method https://stackoverflow.com/a/3737773/807865 which uses the expansion `{1..$i}` - unfortunately they both break if you pass a zero argument. If this is important, you'll want to add a special check for 0. – andyvanee Sep 30 '20 at 18:28
  • Sorry - "break" may have been the wrong phrasing. The both produce the sequence `1 0` which gives two elements. The expected result would be that no lines are output but you would instead get two lines. – andyvanee Sep 30 '20 at 19:00
  • Ahh - I just tried using a different version of `seq` which actually does not iterate backwards... this may be an implementation detail that varies. – andyvanee Sep 30 '20 at 19:04
  • TIL that does seems to be the case - the behavior of `seq` is non-standard and may vary. https://unix.stackexchange.com/questions/64861/how-to-display-numbers-in-reverse-order-using-seq1 – andyvanee Sep 30 '20 at 19:09
  • @andyvanee, the specific thing I intended you to try was `{1..$i}`, which does not expand to a sequence. – jeremysprofile Sep 30 '20 at 20:03
  • Ah, my mistake, my default shell is `zsh` and I didn't double check it i bash. – andyvanee Oct 01 '20 at 16:51
1

Another option:

$ for (( i=1 ; i<=${1} ; i++ ))
do
    echo "${i}"
done
1
2
3
markp-fuso
  • 28,790
  • 4
  • 16
  • 36