4

This question already has an answer here:

I need to store specific number of spaces in a variable.

I have tried this:

i=0
result=""
space() {
    n=$1
    i=0
    while [[ "$i" != $n ]]
    do
        result="$result "
        ((i+=1))
    done
}

f="first"
s="last"
space 5

echo $f$result$s

The result is "firstlast", but I expected 5 space characters between "first" and "last".

How can I do this correctly?

marked as duplicate by Gilles linux Sep 2 '14 at 22:35

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    echo "first$(printf '%*s' 5 ' ')last" should do the trick without looping. printf 'first%*slast\n' 5 ' ' too. Use something like spaces=$(printf '%*s' 5 ' ') ; echo "|$spaces|" to put the spaces into a variable and use them... – yeti Sep 2 '14 at 13:40
7

Use doublequotes (") in the echo command:

echo "$f$result$s"

This is because echo interprets the variables as arguments, with multiple arguments echo prints all of them with a space between.

See this as an example:

user@host:~$ echo this is     a      test
this is a test
user@host:~$ echo "this is     a      test"
this is     a      test

In the first one, there are 4 arguments:

execve("/bin/echo", ["echo", "this", "is", "a", "test"], [/* 21 vars */]) = 0

in the second one, it's only one:

execve("/bin/echo", ["echo", "this is     a      test"], [/* 21 vars */]) = 0

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