hi im new to this shell scripting. I was assigned to develop some code that increased from 0 to 9 in sort of a pyramid. This is what the output should look like.

0
01
012
0123
01234
012345
0123456
01234567
012345678
0123456789

here is my code please help because im confused. some advice would be really appreciated. thanks

#!/bin/bash

cnt=0

while [ $cnt -le 9 ]
do
echo $cnt
while [ $cnt -le 9 ]
do
cnt=$((cnt+1))
echo $cnt
done

done

echo

exit

Dani AI

Generated

A compact, reliable approach is to build each row by appending the next digit to a string and printing that string. That keeps the control flow simple and produces exactly the concatenated output shown in 's example, without an inner loop that reprints values or relies on echo -n portability.

#!/usr/bin/env bash
s=""
for i in {0..9}; do
  s+="$i"
  printf '%s\n' "$s"
done

Why this works: s begins empty and gains one digit per iteration; printf is used instead of echo -n because printf behaves consistently across shells. For a POSIX-/bin/sh safe variant (no brace expansion, no s+=):

#!/bin/sh
i=0
s=""
while [ "$i" -le 9 ]; do
  s=${s}${i}
  printf '%s\n' "$s"
  i=$((i+1))
done

Notes and troubleshooting: 's nested-loop explanation is a good conceptual match but can be simplified by concatenation. 's seq trick is compact but prints space-separated numbers (use concatenation or remove spaces if strict concatenation is required). Common pitfalls to watch for: missing spaces inside [ ] tests, failing to increment loop counters (infinite loops), relying on non-portable echo behavior, and assuming bash features when the script runs under plain sh. If the sequence will include multi-digit numbers (>=10), concatenation becomes ambiguous; consider a delimiter or a different formatting approach in that case.

Recommended Answers

All 3 Replies

Let's work with what you have.

counter initialized to zero
while counter less or equal to nine; do
    row initialized to zero
    while row is less or equal to counter; do
        echo -n row #-n suppress echo from adding a newline
        increment row by one
    done
    echo
    increment counter by one
done
finished

thank you so much. now i understand what i was missing. :)

Good deal - I was thinking you could recreate that pyramid doing a little less work, if you have "seq" to work with:

#!/bin/bash

cnt=0

while [ $cnt -le 9 ]
        do
        echo `seq 0 $cnt`
        cnt=$((cnt+1))
done

echo

exit

host # ./program
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5
0 1 2 3 4 5 6
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7 8 9

Of course, whatever works best for you is what you should go with :)

Best wishes,

Mike

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.