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})
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityNot 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:
function
, which is non-POSIX.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
}
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