Bash Script to Print Star Pattern with Loop
Use a Bash script with a
for loop and echo to print stars line by line, for example: for i in {1..5}; do echo "$(printf '*%.0s' $(seq 1 $i))"; done prints a simple star pattern.Examples
Input5
Output*
**
***
****
*****
Input3
Output*
**
***
Input1
Output*
How to Think About It
To print a star pattern, think of printing one line at a time. Each line has a number of stars equal to the line number. Use a loop to count from 1 to the input number, and print stars accordingly.
Algorithm
1
Get the number of lines to print from the user.2
Start a loop from 1 to the number of lines.3
For each iteration, print stars equal to the current loop number.4
Move to the next line after printing stars.Code
bash
#!/bin/bash read -p "Enter number of lines: " n for ((i=1; i<=n; i++)) do printf '%*s\n' "$i" '' | tr ' ' '*' done
Output
*
**
***
****
*****
Dry Run
Let's trace printing 3 lines of stars through the code
1
Input
User enters n=3
2
First loop iteration
i=1, print 1 star: *
3
Second loop iteration
i=2, print 2 stars: **
4
Third loop iteration
i=3, print 3 stars: ***
| i | Stars Printed |
|---|---|
| 1 | * |
| 2 | ** |
| 3 | *** |
Why This Works
Step 1: Loop controls lines
The for loop runs from 1 to the input number, controlling how many lines to print.
Step 2: Printing stars
Inside the loop, printf with tr prints the exact number of stars for the current line.
Step 3: New line after each print
Each iteration prints stars followed by a newline, creating the pattern line by line.
Alternative Approaches
Using nested loops
bash
#!/bin/bash read -p "Enter number of lines: " n for ((i=1; i<=n; i++)) do for ((j=1; j<=i; j++)) do echo -n "*" done echo done
Uses two loops: outer for lines, inner for stars; more explicit but longer code.
Using seq and xargs
bash
#!/bin/bash read -p "Enter number of lines: " n for i in $(seq 1 $n) do seq -s '*' $i | tr -d '[:digit:] ' done
Uses external commands seq and tr; less efficient but shows command chaining.
Complexity: O(n^2) time, O(1) space
Time Complexity
The script prints stars in nested loops or repeated commands, resulting in roughly n*(n+1)/2 operations, which is O(n^2).
Space Complexity
The script uses constant extra space, only storing counters and printing directly without extra arrays.
Which Approach is Fastest?
Using printf with tr is faster and cleaner than nested loops or external commands.
| Approach | Time | Space | Best For |
|---|---|---|---|
| printf with tr | O(n^2) | O(1) | Simple and efficient star printing |
| Nested loops | O(n^2) | O(1) | Clear logic, easy to understand |
| seq and xargs | O(n^2) | O(1) | Demonstrates command chaining, less efficient |
Use
printf with tr to print repeated characters efficiently in Bash.Beginners often forget to print a newline after each line, causing all stars to appear on one line.