简体   繁体   English

Bash for循环-更改变量名称

[英]Bash for loop - change variable name

I have a for loop that takes a CIDR that contains an illegal character for file names ("/"). 我有一个for循环,该循环使用CIDR,其中包含文件名(“ /”)的非法字符。

part of the command is to save the output with the name of the CIDR. 该命令的一部分是使用CIDR的名称保存输出。

for i in $(more subnets.lst);do shodan download $i-shodan net:$i;done

the download argument is followed by the result of the more command, which are the CIDR (192.168.21.0/24). 下载参数后面是more命令的结果,即CIDR(192.168.21.0/24)。

is there a way in bash to rename a variable while the loop is running ? bash中有什么方法可以在循环运行时重命名变量? I remember doing this years back in batch files by subtracting from the str length, but that won't help me as I just need to replace the "/" with a "-"(or any other compliant char. 我记得几年前在批处理文件中通过从str长度中减去来进行此操作,但这对我没有帮助,因为我只需要用“-”(或任何其他兼容的char)替换“ /”即可。

You can do this with using bash Parameter Expansion: 您可以使用bash参数扩展来做到这一点:

$ echo $var
192.168.21.0/24

$ echo "${var//\//-}"
192.168.21.0-24

So in your command, just use "${i//\\//-}" whenever needed without changing the original value of $i . 因此,在您的命令中,仅在需要时使用"${i//\\//-}" ,而无需更改$i的原始值。 If you want to set variable i to the new value: 如果要将变量i设置为新值:

i="${i//\//-}"

On a side note, use while loop to read lines from a file, not cat , more or brothers, like: 附带说明一下,使用while循环从文件而不是catmore或brothers中读取行,例如:

while IFS= read -r line; do ....; done

我自己解决了:

for i in $(more subnets-test);do shodan download $(echo $i | tr "/" "-") net:$i;done

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

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