Home > OS >  how to print no. from n to 1 from the pattern in shell script
how to print no. from n to 1 from the pattern in shell script

Time:03-03

display the loop

7 6 5 4 3 2 1 
  5 4 3 2 1
    3 2 1
      1

how to print this pattern no idea of printing it from n to 1

read -p "Enter rows:" rows

for ((a=$rows;a>=1;a--))
do
for ((b=$rows;b>$a;b--))
do
    echo -n " "
done
for ((c=1;c<=$a;c  ))
do
    echo -n '* '
    if [ $c = $a ]
    then
        echo -e '\n'
    fi
done
done

please help to print this pattern loop not have enough spaces if i take n as 7 then printing it in 4 line will be difficult for me

CodePudding user response:

The immediate error is that your requirement calls for subtracting two items from the start in each iteration, but you only subtract one.

More generally, probably avoid echo -e entirely; learn to use printf if you need detailed control over newlines etc.

for ((a=$rows; a>=1; a-=2)); do
  printf -v sep "%$((rows - a))s" ""
  for ((b=$a; b>=1; b--)); do
    printf "%s%i" "$sep" "$b"
    sep=" "
  done
  printf '\n'
done

And, as demonstrated here, probably learn to indent your code to show how blocks are nested.

Tangentially, perhaps better to accept the number of rows as a command-line argument rather than prompt interactively for a value. Interactive I/O is pesky when you want to use your script as part of another larger script.

  • Related