简体   繁体   中英

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 . 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. A robust way I know of to do what you want in bash is to use array expansion:

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 . 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 . 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 ).

Edit As @chepner points out in his comment below , there are simpler, more portable techniques for this use case.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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