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?
Your definition of myFunction is wrong. It should be:
or:
Anyway, it looks fine and works fine for me on Bash 3.2.48.
you should put quotes and also, your function declaration is wrong.
And like the others, it works for me as well. Tell us what version of shell you are using.
You could have an extension of this problem in case of your initial text was set into a string type variable, for example:
In this case if you don't pass the status_message variable forward as string (surrounded by "") it will be split in a mount of different arguments.
"$variable": The current track is CDE at DEF by ABC
$variable: The
Im 9 years late but a more dynamic way would be
Another solution to the issue above is to set each string to a variable, call the function with variables denoted by a literal dollar sign
\$
. Then in the function useeval
to read the variable and output as expected.Output is then:
In trying to solve a similar problem to this, I was running into the issue of UNIX thinking my variables were space delimeted. I was trying to pass a pipe delimited string to a function using
awk
to set a series of variables later used to create a report. I initially tried the solution posted by ghostdog74 but could not get it to work as not all of my parameters were being passed in quotes. After adding double-quotes to each parameter it then began to function as expected.Below is the before state of my code and fully functioning after state.
Before - Non Functioning Code
After - Functioning Code
The simplest solution to this problem is that you just need to use
\"
for space separated arguments when running a shell script: