bashprintfleftalign

Left align with printf in bash with unknown width


I am trying to left align with printf in bash with unknown width.

How do I do so?

So sort of like this, but this does not work

max=<enter random number>
printf "%-${max}s|", "Instance"

The point of this is the instance below will be an unknown length that can is dynamic in length.

Example Input

max=10

Example Output

Instance  |

Example Input2

max=12

Example Output2

Instance    |

Solution

  • You can use an * for the length:

    for ((max=8;max<15;max++)); do
        printf "%-*s|\n" ${max} "Instance"
    done
    

    Result:

    Instance|
    Instance |
    Instance  |
    Instance   |
    Instance    |
    Instance     |
    Instance      |