Nested loop in shell
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.
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
)
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.
#!/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
精彩评论