简体   繁体   English

Bash函数参数不适用于范围

[英]Bash function argument is not working with ranges

I'm trying to make a bash function argument work with ranges. 我正在尝试使bash函数参数与范围一起使用。

The following working code which gives the desired results: 以下工作代码给出了预期的结果:

ddos_attack_mirroring_defense() {
    echo $1;
}

ddos_attack_mirroring_defense() Hi NSA ddos_attack_mirroring_defense()NSA大家好

gives: 得到:

Hi NSA

But the following with ranges is not working: 但是下面的范围不起作用:

ddos_attack_mirroring_defense() {
    printf "regx32%0.s" {1..$1};
}

ddos_attack_mirroring_defense 5 returns: ddos_attack_mirroring_defense 5返回:

regx32

instead of: 代替:

regx32regx32regx32regx32regx32

I've tried spaces and other different enclosures such as but they still don't work: 我已经尝试过空格和其他不同的附件,例如,但是它们仍然不起作用:

$(1) ${1}

What am I doing wrong here and how can I solve this? 我在这里做错什么,如何解决呢?

Brace expansion happens before variable expansion. 括号扩展发生在变量扩展之前。 As a result, you can't use variables in ranges, you can only use literals. 结果,您不能使用范围内的变量,而只能使用文字。

See man bash : man bash

The order of expansions is: brace expansion, tilde expansion, parameter, variable and arithmetic expansion and command substitution (done in a left-to-right fashion), word splitting, and pathname expansion. 扩展顺序为:大括号扩展,代字号扩展,参数,变量和算术扩展以及命令替换(以从左到右的方式完成),单词拆分和路径名扩展。

Try this: 尝试这个:

ddos_attack_mirroring_defense() {
     eval printf "regx32%0.s" {1..$1};
}

ddos_attack_mirroring_defense 5

您可以使用Unix实用程序seq产生数字范围。

printf "regx32%0.s" $(seq $1)

You should let the variable expand first before brace expansion. 您应该在括号扩展之前先让变量扩展。 You can use a safe eval to fix that: 您可以使用安全的eval程序来解决此问题:

ddos_attack_mirroring_defense() {
    eval "printf 'regx32%0.s' {1..$1}"
}

Another way of achieving this: 实现此目的的另一种方法:

ddos_attack_mirroring_defense() {
    perl -e "print 'regx32'x$1"
}

A safer alternative to using eval is 使用eval更安全替代方法是

ddos_attack_mirroring_defense() {
    printf "regx32"
    for ((i=1; i<=$1; i++)); do
        printf "%0.s" "$i"
    done
}

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

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