我正在编写一个Bash脚本,我需要在Bash脚本中传递一个包含空格的字符串到函数。

例如:

#!/bin/bash

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

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

当运行时,我期望的输出是:

firstString
second string with spaces
thirdString

然而,实际输出的是:

firstString
second
string

是否有一种方法可以将带有空格的字符串作为一个参数传递给Bash中的函数?


当前回答

对我来说很简单的解决方案——引用$@

Test(){
   set -x
   grep "$@" /etc/hosts
   set +x
}
Test -i "3 rb"
+ grep -i '3 rb' /etc/hosts

我可以验证实际的grep命令(多亏了set -x)。

其他回答

对我来说很简单的解决方案——引用$@

Test(){
   set -x
   grep "$@" /etc/hosts
   set +x
}
Test -i "3 rb"
+ grep -i '3 rb' /etc/hosts

我可以验证实际的grep命令(多亏了set -x)。

更有活力的方法是:

function myFunction {
   for i in "$*"; do echo "$i"; done;
}

你应该加上引号,而且,你的函数声明是错误的。

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

和其他人一样,这对我也适用。

这个问题最简单的解决方案是,当运行shell脚本时,你只需要使用“\”作为空格分隔的参数:

#!/bin/bash
myFunction() {
  echo $1
  echo $2
  echo $3
}
myFunction "firstString" "\"Hello World\"" "thirdString"

你对myFunction的定义是错误的。它应该是:

myFunction()
{
    # same as before
}

or:

function myFunction
{
    # same as before
}

不管怎样,它在Bash 3.2.48上看起来很好,对我来说也很好。