5

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?

kpmDev
  • 189
  • 2
  • 3
  • 8
  • 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... –  Sep 02 '14 at 13:40

1 Answers1

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
chaos
  • 47,463
  • 11
  • 118
  • 144