在 Bash 中将带有空格的字符串作为函数参数传递 [英] Passing a string with spaces as a function argument in Bash

查看:24
本文介绍了在 Bash 中将带有空格的字符串作为函数参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

例如:

#!/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

然而,实际输出的是:

firstString
second
string

有没有办法将带有空格的字符串作为单个参数传递给 Bash 中的函数?

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

推荐答案

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

You should add 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.

这篇关于在 Bash 中将带有空格的字符串作为函数参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆