简体   繁体   English

将空格字符串作为参数传递给函数

[英]Passing spaced string as argument to function

I'm trying to make an install function like this: 我试图做这样的安装功能:

function call_fedora(){
        yum -y install $1;
}

function network_tools(){
        tools='net-tools traceroute nmap'
        call_fedora $tools;
}

But when I call network_tools function, only net-tools is passed as argument to call_fedora . 但是,当我调用network_tools函数时,只有net-tools作为参数传递给call_fedora I would like the call to be: 我希望电话是:

yum -y install net-tools traceroute nmap

Bash is actually passing call_fedora the entire string net-tools traceroute nmap as one argument. Bash实际上将整个字符串net-tools traceroute nmap传递给call_fedora作为一个参数。 A robust way I know of to do what you want in bash is to use array expansion: 我知道在bash中执行所需操作的一种可靠方法是使用数组扩展:

function call_fedora(){
        yum -y install "$@"     # "$@"  means  "$1" "$2" ...
}

function network_tools(){
        tools=(net-tools traceroute nmap "some funky package with spaces")
        call_fedora "${tools[@]}"       
                # keep relationship between array elements and args of call_fedora
}

The "$@" means that each parameter to call_fedora will be passed as a separate parameter to yum . "$@"表示将call_fedora每个参数作为单独的参数传递给yum The double-quotes mean the parameters can include spaces (it's a good habit to have). 双引号表示参数可以包含空格(这是一个好习惯)。

Then, you need to make sure your tools are passed as separate arguments to call_fedora . 然后,您需要确保将您的tools作为单独的参数传递给call_fedora Making them an array makes it easy to keep them separate. 将它们制成数组可以很容易地将它们分开。 The "${tools[@]}" gives you each array element as a separate parameter, properly quoted ( original source ). "${tools[@]}"为您提供每个数组元素作为单独的参数,并用正确的引号引起来( 原始来源 )。

Edit As @chepner points out in his comment below , there are simpler, more portable techniques for this use case. 编辑 @chepner在下面评论中指出,此用例有更简单,更可移植的技术。

我建议将$1替换$1 $@

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM