0

Is there a pure bash way to add trailing whitespaces with something like parameter substition in the example above I am using printf in conjunction with command substition witch is not that performant

declare -ir _CONST_VARIABLE_LENGTH='30' _CONST_SUBTRACTOR='3'
declare some_var='here is a string'
declare new_var

new_var="$(printf "%-$((_CONST_VARIABLE_LENGTH-_CONST_SUBTRACTOR))s" "$some_var")"

# what i want, but doesn't work
# ${var:0:LENGTH} only goes till actually length and won't add something if LENGTH is greater than actual var lenght
new_var="${some_var:0:$((_CONST_VARIABLE_LENGTH-_CONST_SUBTRACTOR))}"
mikee
  • 29
  • 3
  • 1
    [`printf` is a bash builtin](https://www.gnu.org/software/bash/manual/bash.html#Bash-Builtins) – Sean Bright Feb 04 '21 at 16:29
  • (not just bash, POSIX-standardized; more tightly standardized than `echo`, for that matter, and thus more reliable -- for more on that, see Stephane's excellent answer on [Why is `printf` better than `echo`?](https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo)) – Charles Duffy Feb 04 '21 at 16:31
  • BTW, note `printf -v varname fmtstring ...values...` to have `printf` directly assign to `varname`. If you're only targeting bash, `varname=$(printf fmtstring ...)` is an antipattern -- needlessly much slower to run. – Charles Duffy Feb 04 '21 at 16:33

0 Answers0