0

Any standard way to make the '%-6s' format for printf dynamic?

function justify
{
echo "$(printf '%-6s' $1)"
}

I tried inserting variable into the format but I'm getting Error processing format error.

$(printf '%-${2}s' ${1})

3 Answers 3

0

Not totally sure what you were intending by passing the command substitution to echo, but this should do the trick:

justify() {
    printf "%-${2}s\n" "$1"
}

If you had $1 unquoted in order to pass multiple arguments, consider using "$@" instead.

There are a few things to note in relation to your existing attempt:

  1. Variables aren't expanded in single quotes, use double quotes.
  2. There's no need to use a command substitution, just call the command directly.
  3. (Optional) Avoid function, which is non-POSIX.
1
  • thank you for this and this solve my problem. I doing a refactoring of old bash scripts and this command substitution didn't caught my attention. and ++ for additional explanation there.
    – resti
    Feb 15, 2022 at 2:26
0

Shell variables are not expanded inside single quotes; the $ is treated as a literal dollar sign. You should use double quotes to have ${2} expanded as a shell variable:

printf "%-${2}s" ${1}

Your question isn’t completely clear as using command substitution to pass the output of printf '%-6s' $1 as the input parameters to echo removes whatever space characters were printed by the printf command. It seems to me that your function would be better written as:

justify()
{
    printf "%-${2}s" $1
}
1
  • 1
    thank you for this, just like the accepted answer but with additional explanation the effect of echo to printf output
    – resti
    Feb 15, 2022 at 2:36
0

At least in bash 4.4+, it appears to be possible to use a C style1 * to access the next available argument as a width or precision. So for example:

justify ()
{
    printf '%-*sbar\n' "$2" "$1"
}

$ justify foo 6
foo   bar

(bar suffix just included to make the width of foo apparent); or

pround ()
{
    printf '% *.*f\n' "$2" "$3" "$1"
}

$ pround 123.45678 12 3
     123.457

1 see man 3 printf for example

1
  • this for demo examples, and rounding function there, and yes this solution works for me as well, just excluding the sbar
    – resti
    Feb 15, 2022 at 2:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .