Ahmad Nadaf
Ahmad Nadaf

Reputation: 31

Bash Loop Program

This is not a homework by anyway to start with this part of a program I'm working on. what I'm trying to do is to print this shape using bash loops.



********
  ****
   **

This is what I have so far, it will print the shape, but I'm trying to find a way jut to use on echo statement, so for example if I put Var="8" and then decrement var by 2 and print them on the same line. Any help is welcomed thanks

 #!/bin/bash 
         COUNTER="1"
            until [  $COUNTER -lt 1 ]; do
echo  "**********"
echo  " ******** "
echo  "  ******  "
echo  "   ****   "
echo  "    **    "

              let COUNTER-=1
        done

Upvotes: 1

Views: 952

Answers (1)

Charlie Martin
Charlie Martin

Reputation: 112424

You can do a loop with arithmetic in bash using the $((expr)) notation, much as you would in any other programming language. So, write a function like

function printNx {
   N=$1
   X=$2
   count=0
   while $(($count++ < $N))
   do
      echo -n $X
   done
   echo ""
}

(Don't depend on the syntax until I've checked it. I program in about a zillion scripting languaes and get them confused.)

Update

Almost had it:

bash $ cat foo.bash
function printNx {
   N=$1
   X=$2
   count=0
   while [ $((count ++ )) -lt $N ]
   do
      echo -n "$X"
   done
   echo ""
}

printNx 5 '*'
bash $ bash foo.bash
*****
bash $ 

Upvotes: 1

Related Questions