Storing whitespace in a shell script variable

7,107

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:

[email protected]:~$ echo this is     a      test
this is a test
[email protected]:~$ 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:
7,107
Author by

kpmDev

Updated on September 18, 2022

Comments

  • kpmDev 2 months

    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?