0

I created a function and every time I execute the script it spawns thousands of processes until the box crashes. I am not sure what is going wrong. Any help is appreciated.

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
4
  • BTW -- if [ $method == "ping" ] should be if [ "$method" = ping ]. Expansions need to be quoted to prevent string-splitting and globbing; constant strings with values known not to contain literal spaces, glob characters, &c. don't. And == isn't a valid operator in test -- bash offers it as an extension, which is why your code is working when you test it, but POSIX only specifies =. Commented Dec 13, 2016 at 1:35
  • ...consider running code through shellcheck.net before asking about it here. Commented Dec 13, 2016 at 1:36
  • @SachinMokashi, re: your edit -- multi-line code blocks should be formatted with four-space indents, not backticks. See the {} button in the editor. Commented Dec 13, 2016 at 1:39
  • ...btw, the parens in (ping ...) contributed to the problem by running code in a subprocess, causing a fork -- otherwise this would have only had one process looping but not crashed the machine. Commented Dec 13, 2016 at 1:41

1 Answer 1

2

Your function is recursing.

Use command ping to use the real ping command, rather than your function -- or, better, name it something other than ping.

That is:

# 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
}

Or, better:

# 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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Wow I have been staring way to hard at it and totally missed it. Fixed it, Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.