-->

DEVOPSZONES

  • Recent blogs

    How to Print a grid or matrix using Bash scripting

     To print a grid or matrix using the bash scripting, we  need to write loop within a loop. Which can be acheived using the below piece code.

    Print 4X4 Grid:

    #!/bin/bash
    rows=4
    columns=4
    for ((i=0;i<$rows;i++))
    do
        for ((j=0;j<$columns;j++))
        do  
            printf $j
        done
        printf "\n"
    done

    Output:

    0123

    0123

    0123

    0123

    Bash matrix
    Bash matrix

    Print a matrix using a single array:

    #!/bin/bash
    
    # We create an example array 'a' containing 16 values:
    # array a = ( 0 1 2 3 4 ... 14 15 )
    a=({0..15})
    
    echo 'Linear array:'
    echo ${a[*]}
    
    # We now display this array 'a' in a 4x4 grid
    echo 'Matrix array:'
    for row in {1..4}; do
        for col in {1..4}; do
            echo -n ${a[((4*row+col-5))]}$'\t'
        done
        echo
    done
    

    Output:

    Linear array:

    0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

    Matrix array:

    0       1       2       3

    4       5       6       7

    8       9       10      11

    12      13      14      15

    Bash_matrix_linear_array
    Bash_matrix_linear_array

    Display "*" in a 4X4 Grid:

    #!/bin/bash
    
    # We now display this '*' in a 4x4 grid
    echo 'Matrix array:'
    for row in {1..4}; do
        for col in {1..4}; do
            echo -n *$'\t'
        done
        echo
    done
    Display_star_in_matrix
    Display_star_in_matrix

    Please share and comment if it is useful.

    No comments