Passing a string with spaces as a function argument in bash

Grant Limberg picture Grant Limberg · Dec 31, 2009 · Viewed 223.2k times · Source

I'm writing a bash script where I need to pass a string containing spaces to a function in my bash script.

For example:

#!/bin/bash

myFunction
{
    echo $1
    echo $2
    echo $3
}

myFunction "firstString" "second string with spaces" "thirdString"

When run, the output I'd expect is:

firstString
second string with spaces
thirdString

However, what's actually output is:

firstString
second
string

Is there a way to pass a string with spaces as a single argument to a function in bash?

Answer

ghostdog74 picture ghostdog74 · Dec 31, 2009

you should put quotes and also, your function declaration is wrong.

myFunction()
{
    echo "$1"
    echo "$2"
    echo "$3"
}

And like the others, it works for me as well. Tell us what version of shell you are using.