Bash函数和for循环

时间:2016-12-13 01:27:43

标签: bash

我创建了一个函数,每次执行脚本时,它都会生成数千个进程,直到该框崩溃。我不确定出了什么问题。任何帮助表示赞赏。

ping () {
    for i in {1..254};
    do
        (ping -c1 -W1 10.0.0.$i)
    done
while true;
do
    read -rep $'What method do you want to use' method
    if [ $method == "ping" ];
    then
        ping
    else
        echo "Wrong method"
done

1 个答案:

答案 0 :(得分:2)

您的功能正在递归。

使用command ping来使用真正的ping命令,而不是使用您的函数 - 或者更好的是,将其命名为ping以外的其他命令。

那是:

# bad: shadows "ping" with a command that does something different
# ...but at least it doesn't recurse
ping() {
  for ((i=1; i<=254; i++)); do
    command ping -c1 -W1 "10.0.0.$i"
  done
}

或者,更好:

# good: name doesn't shadow the traditional ping command
pingAll() {
  for ((i=1; i<=254; i++)); do
    ping -c1 -W1 "10.0.0.$i"
  done
}