0

I am a beginner at shell programming. I have a problem related to nested loops in shell scripts. I want to get output like this:

Input: 4

Output:

*
**
***
****

This is the script I am using so far:

echo "input : "
read a
for ((i=0; i<a; i++))
do
   for ((j=0; j<i; j++))
   do
       echo "*"
   done
   echo "\n"
done

When trying to execute my program I get an error: Bad for looping.

Thanks in advance.

3 Answers 3

1

try this

echo "input : "
read a
for ((i=0; i<a; i++))
do
   for ((j=0; j<=i; j++))
   do
       printf "*"
   done
   echo
done

To not print newlines, you can use printf (or the echo -n but is not as portable as printf)

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

2 Comments

thanks you for advance. are u prefer printf than echo in shell scripting?
Actually, it depends on individuals. If I am not writing portable scripts, i just use echo for simple display. if i want string formatting, i use printf.
1

I don't get any error with the script! Though the echo needs to be different like below:

echo "input : "
read a
for ((i=0; i<a; i++))
do
   for ((j=0; j<i; j++))
   do
       echo -ne "*"
   done
   echo -ne "\n"
done

You might try adding $ in front of the variables while accessing them though. It is not giving any errors for me.

4 Comments

echo -e "\n" will print 2 new lines, echo -e "" is good enough.
@anubhava - right edited to echo -ne "\n" to make it consistent and clearly convey the newline meaning
@manojids, just echo will provide the same output as echo -ne "\n"
@ghostdog74 - I have explained in my comment above that it is to convey the newline in echo more clearly since obviously the OP was not aware of it.
0
#!/bin/bash

print_starry_row()
{
    n="$1"
    for ((i=0;i<n;i++))
    {
        echo -n "*"
    }
    echo
}

read -p "Enter number of stars? " num

if [[ "$num" -eq $num ]]
then
    for ((i=1;i<=num;i++))
    {
        print_starry_row $i
    }
else
    echo "You must enter a valid integrer"
fi

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.