im a beginner, And i want to writing a script ('for' loop) -
- Requests a number
- Multiply the number by 2 and start a raw of asterisks And presents as here: (for example the number is 4)
********
******
****
**
****
******
********
im a beginner, And i want to writing a script ('for' loop) -
********
******
****
**
****
******
********
#!/bin/bash
read -p 'Number please: ' n
{
for (( i=0; i<n-1; ++i )); do
printf '%*.*d\n' "$(( 2*n-i ))" "$(( 2*(n-i) ))" 0
done
for (( i=n-1; i>=0; --i )); do
printf '%*.*d\n' "$(( 2*n-i ))" "$(( 2*(n-i) ))" 0
done
} | tr 0 '*'
The above script reads a number from the user into the variable n. It then creates the shape in two arithmetic for loops.
The first loop creates the top half of the shape, while the second loop creates the middle ** and the lower half of the shape.
The printf statement in each loop is identical, and only the value of i, the loop variable, changes.
The printf format used here, %*.*d, means "allocate space according to the first argument, to print a zero-filled integer with the width of the second argument". The actual integer to print is 0 (the third argument). The 1st and 2nd arguments given to printf causes it to print triangular shapes of 0 as i changes.
The 0 characters are then changed into * characters using tr.
Testing:
$ bash script.sh
Number please: 10
********************
******************
****************
**************
************
**********
********
******
****
**
****
******
********
**********
************
**************
****************
******************
********************
See also man printf.
taced version printf '%s\n' "$tmp"; printf '%s\n' "$tmp"|tac
– αғsнιη
Nov 20 '20 at 16:46
tac on my non-Linux system... :-) But still, good call. I might investigate it later.
– Kusalananda
Nov 20 '20 at 16:47
tail -r https://unix.stackexchange.com/a/114043/72456
– αғsнιη
Nov 20 '20 at 16:50