简体   繁体   English

如何正确打印作为参数传递给 Bash 函数的字符串?

[英]How to correctly print a string passed as an argument to a Bash function?

I'm writing shell(bash) script like this:我正在编写这样的 shell(bash) 脚本:

output_function()
{
    for i in "$@"
    do
        echo $i
    done
}

process_funtion()
{
    string=process some thing
    output_function $string
}

for example, after process some thing, string is例如,在处理一些事情之后,字符串是

i am line 1
i am line 2

I want to print these 2 line as it is, but actually I got我想按原样打印这两行,但实际上我得到了

i
am
line
1
i
am
line
2

Also this NOT work:这也不起作用:

#!/bin/bash

output()
{
    printf '%s\n' "$@"
}

output `ifconfig`

result is:结果是:

...
2000
inet6
fe80::6de5:743c:addd:7c5a%utun0
prefixlen
64
scopeid
0xa
nd6
options=201<PERFORMNUD,DAD>

And this NOT work also:这也不起作用:

#!/bin/bash

output()
{
    printf '%s\n' "$*"
}

output `ifconfig`

result is all in one line.结果都在一行中。

how to fix this?如何解决这个问题? thank you~谢谢~

You need to enclose the function arguments in double quotes to prevent word splitting :您需要将函数参数括在双引号中以防止分

output "$string"

instead of而不是

output $string

And you don't really need a loop to print the contents of $@ , you could simply write:而且你真的不需要循环来打印$@的内容,你可以简单地写:

printf '%s\n' "$@"

See also:另见:

In your example:在你的例子中:

output()
{
    printf '%s\n' "$*"
}

output `ifconfig`

the result of ifconfig also needs to be quoted, otherwise the result will be split into multiple arguments (using $IFS) before being passed to the function. ifconfig 的结果也需要引用,否则在传递给函数之前,结果将被拆分为多个参数(使用 $IFS)。 So所以

output "`ifconfig`"

should do.应该做。

See Bash Reference Manual: 3.4.2 Special Parameters for using $* and $@ correctly and the difference between both.请参阅Bash 参考手册:3.4.2正确使用$*$@ 特殊参数以及两者之间的区别。

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

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