tags:

views:

409

answers:

3

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?

+6  A: 

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.

ghostdog74
+2  A: 

Your definition of myFunction is wrong. It should be:

myFunction()
{
    # same as before
}

or:

function myFunction
{
    # same as before
}

Anyway, it looks fine and works fine for me on Bash 3.2.48.

R Samuel Klatchko
A: 

It also worked for me if I declared "myFunction" with the function keyword:

function myFunction
{
    # same as you have
}
Andy White