Problem With Bash Script--Beginner Question

Very much a beginner here. I am teaching myself how to write Bash Scripts. I am going through a lesson called “Shell Scripting for Beginners – How to Write Bash Scripts in Linux” and so far, so good.

I am however having a problem trying to expand on a sample in the lesson regarding looping with numbers. When I create a script as described in the lesson:


for i in {1…5}
do
echo $i
done


And run the script, the output is as expected. My screen shows, vertically, the numbers 1 through 5. However, I would like to allow the use of a variable, input by the user, as the “top” number in the count. For example, I want the user to enter the number they want the script to count to, and have the vertical list go from 1 to that number. Here’s the script I wrote:


echo “Runs a loop”
read -p "What do you want the loop to count to? " count
for i in {1…$count}
do
echo $i
done


And here’s the output (I typed in the number “7”). As you can see, the script did not perform as expected. Instead of counting from 1 through 7, it simply printed the following:


Runs a loop
What do you want the loop to count to? 7
{1…7}


So, any suggestions would be very much appreciated.

Thank you…

it is possible you are skipping ahead too much so you haven’t learned how to do this correctly.
for ((i = 1; i <= $count; i++))
I believe this is how it would be written if you want to count up to a variable.
The construct that you are currently using is called a range construct and doesn’t work with variables.

Thank you hbar1st. I gave your line of code a try but still have problems. I suspect you are correct–I am getting a bit ahead of myself! I appreciate your suggestion. (BTW–the line of code that you provided, if I remember correctly, looks similar to a C line of code, but again, there I’m far from knowing more than just the basics.) :slight_smile:

Yeah I am not sure what error you got but this style is the c style of writing for loops, yeah.

1 Like