Shell Script to print pyramid of Stars

The Basics

So here we will print the pyramid of stars in two parts as shown below. We will loop through the number provided by the user and print the first half of the stars using a for loop and other half using another for loop. The spaces and new line characters are added in a different section.

The Script

1. Edit the file /tmp/star_pyramid.sh and add the below script into it:

#!/bin/bash
makePyramid()
{
  # Here $1 is the parameter you passed with the function i,e 5
  n=$1;

  # outer loop is for printing number of rows in the pyramid
  for((i=1;i<=n;i++))
  do

      # This loop print spaces required
      for((k=i;k<=n;k++))
      do
        echo -ne " ";
      done

      # This loop print part 1 of the the pyramid
      for((j=1;j<=i;j++))
      do
      echo -ne "*";
      done

      # This loop print part 2 of the pryamid.
      for((z=1;z<i;z++))
      do
      echo -ne "*";
      done
      
      # This echo is used for printing a new line
      echo;
  done
}

# calling function
# Pass the number of levels you need in the parameter while running the script.
makePyramid $1

2. Provide executible permissions on the script.

# chmod +x /tmp/star_pyramid.sh

3. While running the script provide the number of levels you want in the output. For example:

$ /tmp/star_pyramid.sh 10
          *
         ***
        *****
       *******
      *********
     ***********
    *************
   ***************
  *****************
 *******************

Another way

Here is another way to print the pyramid of stars using shell script.

#!/bin/bash

clear
echo -n "Enter the level of pyramid: "; read n

star=''
space=''

for ((i=0; i<n; i++ ))
do
space="$space "
done

echo "$space|"

for (( i=1; i<n; i++ ))
do

star="$star*"
space="${space%?}"
echo "$space$star|$star";

done

Make the script executable and run it.

$ /tmp/star_pyramid.sh
Enter the level of pyramid: 10
          |
         *|*
        **|**
       ***|***
      ****|****
     *****|*****
    ******|******
   *******|*******
  ********|********
 *********|*********

Pyramid of Numbers using shell script

Similar to the above 2 examples, you may also print a pyramid of numbers using the below script.

#!/bin/bash

read -p "How many levels? : " n

for((i = 0; i < n; i++))
do
k=0
while((k < $((i+1))))
do
echo -e "$((i+1))\c"
k=$((k+1))
done

echo " "
done

Make the script executable and run it.

$ /tmp/star_pyramid.sh
How many levels? : 5
1
22
333
4444
55555
Related Post