Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question

marked as duplicate by Gilles Sep 2 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 at 13:40

1 Answer 1

up vote 4 down vote accepted

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
share|improve this answer

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