1

I want create a yaml configuration file from a sh script. So I need to add multiple spaces to a variable like that:

SERVERS=""
for i in $(seq 1 5); do
    SERVERS="$SERVERS      -server`printf "%03d" $i`.$URL\n"
done

But the spaces are reduced to only one space. How do I ensure that the spaces aren't replaced?

2
  • Note that you aren't adding newlines to your string; you are adding two literal characters "\" and "n". Commented Feb 19, 2013 at 14:25
  • I realized this already. When I print the variable by echo "$SERVERS", the \n is interpreted as a newline, but when I store it in a file, it just dumps "\n". How do I make a real line break? Commented Feb 20, 2013 at 8:40

2 Answers 2

2

I suspect that you forgot to use double quotes when you echo $SERVER =)

SERVERS=""
for i in $(seq 1 5); do
    SERVERS="$SERVERS      -server$(printf "%03d" $i).$URL\n"
done
echo "$SERVER"

Output :

      -server001.\n      -server002.\n      -server003.\n      -server004.\n(...)

That's the rules of the (not so) terrific word splitting


Another solution using :

perl -le 'for (1..5) { print "   -server$_"}' | tee -a file.yaml

Or using :

awk 'BEGIN{for (i=1; i<=5; i++) print "   -server"++c}'  |
    tee -a file.yaml
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I really just forgot to add double quotes.
0

What do you ultimately do with SERVERS? Rather than try to build up a multi-line string, something like this might be better:

for i in $(seq 1 5); do
    echo "     -server$(printf "%03d" $i).$URL"
done >> file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.