I'm trying to align a string variable in Bash. This is the desired behaviour.

if str1="123"  , then str2="     123"
if str1="1234" , then str2="    1234"
if str1="12345", then str2="   12345"

etc. I've seen how to do it to print with printf, but I need to do it inside the variable without printing it out.


Assuming the variable only contains single-byte, single-width characters:

printf -v str2 %8s "$str1"

If they may contain multi-byte (but still single-width) characters, you can do instead:

printf -v str2 %8s%s '' "$str1"
str2=${str2: -8}

(note however that that one truncates values larger than 8 characters).

Here bash's printf builtin command supports -v to store the result of printf into a variable, but even if it didn't you could use command substitution:

str2=$(printf %8s "$str1")
  • Thank you, very much! I'm trying it now and it will most probably do what I needed.It will help a lot! :) Nov 6 '18 at 16:47
  • If I'm understanding it correctly, the -v makes the printf command abstain from printing the result on the screen, instead attributting it to the variable that follows it, is that correct? Nov 6 '18 at 16:53
  • @JairoAlves, yes. See info bash printf or help printf within bash for details. Nov 6 '18 at 17:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.