I have the following code

printf "%8s.%s\n" "$RANDOM" "$RANDOM" "$RANDOM" "$RANDOM" "$RANDOM" "$RANDOM" "$RANDOM" "$RANDOM"

That produces the expected output


I would like to save this output with leading spaces in a variable for later uses like this

printf -v output "%8s.%s\n" "$RANDOM" "$RANDOM" "$RANDOM" "$RANDOM" "$RANDOM" "$RANDOM" "$RANDOM" "$RANDOM"

However, if i try to print/echo the variable $output, leading spaces are gone:

  • note that what you're getting is a number of the form x.y, where both x and y are within the range 0..32767. Which in particular means that the fractional part can never more than about 1/3. If you want something where the fractional part is somewhat evenly distributed, you could use RANDOM divided by 32768, e.g. printf "%d.%d\n" $RANDOM $(( RANDOM * 1000 / 32768 )), or in a shell like Zsh that supports floating point arithmetic: printf "%.3f\n" $(( RANDOM + RANDOM / 32768.0 )) – ilkkachu Jul 17 at 19:08

I'm guessing that you are using the variable output unquoted, as in

printf '%s\n' $output

That would make the shell split the string in the variable on whitespaces (spaces, tabs, and newlines by default), i.e. it would delete the leading indentation. You'd still get four lines of output from this, only because the format string of printf is reused for each word.

With echo $output, you'd get your data on a single line since that is what echo does, it outputs each argument (the split-up words from your string) with spaces between them.

Instead make sure that you are double quoting the expansion of $output:

printf '%s' "$output"

(I'm not putting a \n in the format string here since that would output an empty line at the end of your string, as it already ends with a newline).

See also:

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.