0

I have been attempting to create a file out of my loop in bash , I was successful in generating the file with the following code

for ((i = 0; i <= 5; i++)); do
  for ((j = i; j <= 5; j++)); do
    echo -e "$i $j" >> numbers.txt
  done 
done

however I want my results to be out in the following fashion

 01

 02

 03

etc.

But the result I am getting is similar to this

0 0 1 0 2 0 3 0 4 0 5 1 1 1 2 1 3 1 4 1 5 2 2 2 3 2 4 2 5 3 3 3 4 3 5

How can I solve this ?

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
JavaFreak
  • 93
  • 3
  • 3
  • 11
  • 2
    If you don't want the space between the two digits, then you can just omit it. Or - better - use printf for formatted output printf '%d%d\n' "$i" "$j". – steeldriver Jun 24 '16 at 19:59
  • Hello, thank you for your reply .. i want the ouputs to be on a new line, meaning each pair generated. so the n pair is on a line and the n+1 pair on a new line and so on – JavaFreak Jun 24 '16 at 20:00
  • @heemayl my text was formatted right :P i am not getting the results on a new line am getting all of them on the same line – JavaFreak Jun 24 '16 at 20:01
  • 1
    Are you sure? Each should be on its own line unless you used echo -n. What platform are you on? – leekaiinthesky Jun 24 '16 at 20:44
  • If you're really getting everything on the same line, you didn't run the code you showed us. – Gilles 'SO- stop being evil' Jun 24 '16 at 22:43
  • You don't need C-style for loops here: for i in {0..5}; do for j in {1..5}; do printf "%d%d\n\n" "$i" "$j"; done; done – cas Jun 25 '16 at 03:41

2 Answers2

1
for ((i = 0; i <= 5; i++)); do
  for ((j = i; j <= 5; j++)); do
    echo -e "${i}${j}\n" >> numbers.txt
  done 
done

Should do the trick. I removed the space, I prefer using {}'s around my variables and \n puts in new line.

1

bash has C-style for loops, but stylistically they're a little odd to use when you don't have to. And if you really do absolutely have to, you might be using the wrong language. (For this use case shell is fine, of course.)

A much more shell-like way to do this (in my opinion) is:

for i in {0..5}; do for j in $(seq "$i" 5); do echo "$i$j"; done; done

Here is another approach:

(set {0..5}; for i; do for j; do [ "$i" -le "$j" ] && echo "$i$j"; done; done)

I write these as one-liners suitable for an interactive shell, but they work equally well in structured form (which would usually be preferable in a script):

set {0..5}
for i; do
  for j; do
    [ "$i" -le "$j" ] &&
      printf '%d%d\n' "$i" "$j"
  done
done
Wildcard
  • 36,499