0

I'm currently trying to make a script in bash that uses some specific numbers. It's for a different program but for the example, I'll use this basic ping script.

In this example, the script would ping 192.168.1.215, 216, etc. up to 225

for i in `seq 215 225`; do ping -c 1 -W 1 192.168.1.$i ; done

My question is - is there a way to set a variable (in this case, 'i') to a specific list of numbers, rather than a range?

For example, have it try 215, 217, and 220, specifically - without trying any numbers in between?

1
  • 1
    See: help for or if you prefer man page style: help -m for | less Commented Jun 8, 2015 at 2:53

1 Answer 1

3
for i in 215 217 220; do ping -c 1 -W 1 192.168.1.$i; done

Simply list the numbers you want tested. If you want to pass the numbers into the script, then maybe:

for i in "$@"; do ping -c 1 -W 1 192.168.1.$i ; done

or you could even omit the double quotes (but generally double quotes are desirable).

Sign up to request clarification or add additional context in comments.

3 Comments

Might as well quote the $i expansion as well (in the bottom, user-input-driven case); that way malicious arguments can't add extra flags to ping (ie. "1 -f").
@CharlesDuffy: Not convinced it's necessary; it would be GIGO. It depends in part on who it is intended for —if Granny is going to use it, maybe you worry, but then you do all sorts of extra validation. And the chances of Granny knowing which numbers in the 192.168.1.* domain to test are limited. And in the case where the numbers are explicitly listed, adding the double quotes does absolutely nothing of any value whatsoever.
Yes, I was explicit that this only made any difference in the user-input-driven case. Sure, garbage in means garbage out, but that doesn't mean there's no value to making at least minimal effort (and two characters is quite minimal, no?) to make bad inputs cause graceful failures.

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.