0

I am new to bash scripting and trying to learn a few things. Here is the code I have tried:

n=$1
shift

echo "Printing your name $n times"
count=1
for ((i=1;i<=$n;i++))
do
    echo $@ -$i
    count='expr[$count+1]'
done

echo 'New Model'
count=1
while ["$count" -le "$n"]
do
    echo $@ -$i
    count='expr[$count+1]'
done

The for loop works fine, but the while loop is not printing the desired result. the Result of the for loop and while should be the same. Could you please tell me where I have gone wrong. Thank you.

3 Answers 3

4

One problem is that you need spaces around the brackets, so that bash knows that they're separate words. That is, change this:

while ["$count" -le "$n"]

to this:

while [ "$count" -le "$n" ]

Another is that this:

count='expr[$count+1]'

actually sets the variable count to the specific string expr[$count+1]. What you seem to mean is this:

count=$((count+1))

which increases the value of count by 1.

Sign up to request clarification or add additional context in comments.

4 Comments

The [ is actually a link to /bin/test (ok, in bash it's a builtin, but that's where it comes from). So [ is a word (just like ls) and that's why it needs the space.
@BenJackson: I think the spaces would be needed even without that; note that [[ requires spaces as well, even though it is magical in other ways.
Hey, Thank you very much for the info, but what I did not understand is count='expr[$count+1]' worked in for loop but did not work in while loop, can you please tell me why? Thank you.
@surpavan: It doesn't work in the for-loop; but nothing in the for-loop uses the value of count, so it doesn't matter that it doesn't work there.
2

another ways to increment variable:

#!/bin/bash

count=1

#count=`expr $count + 1 `
#(( count++ ))
#count=$[$count + 1]
#count=$[count + 1]
#let count=count+1
#let count++
#count=$(( count + 1 ))

echo $count

Comments

1

try this:

count=1
while [ "$count" -le "$n" ]
do
echo $@ -$i
count=`expr $count + 1`
done

there needs to be a space in the while condition. and the increment of count needs the back-quote, not a single quote, to execute the command and assign it to a variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.