-1

I have been trying to write this for loop to a file:

echo "for i in 1 2 3 4; do echo $i; done" >> test.sh

It should make a file that will print the numbers 1 to 4. But whenever I run this the output is 4 4 4 4 each appearing on a new line.

When I look at the sh file the do echo $i I entered has changed to do echo 4. The rest of the code is the same.

Is there some syntax that I'm missing?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578

1 Answers1

2

$i is being evaluated by the outer shell. Escape the dollar sign to ensure a literal dollar sign is echoed.

echo "for i in 1 2 3 4; do echo \$i; done" >> test.sh

Or use single quotes to prevent any expansion within the string.

echo 'for i in 1 2 3 4; do echo $i; done' >> test.sh
John Kugelman
  • 349,597
  • 67
  • 533
  • 578