-1

I with to monitor if my access points pingable and store results into 0-1 string

I wrote a script but it works wrong

#/bin/bash

access_points=("tplink2" "redmi1")
#results=("A")
declare -a results

for val in "${access_points[@]}"
do
    ping -c 4 -w 10 $val 2>&1 >/dev/null
    if [ $? -eq 0 ]
    then
       online="+"
    else
       online="-"
    fi
    results[${#results[@]}]=$online
done
echo "${resutls[*]}"
echo $results

Why? Can I collect values not into arrays but into space separated strings?

1
  • ! missing in the shebang. Commented Dec 16, 2021 at 21:41

1 Answer 1

3

To add an element to an array, use +=:

results+=("$online")

Also note that resutls and results don't refer to the same variable.

BTW, you don't have to check $?, you can run the command directly in the if:

#! /bin/bash

access_points=("tplink2" "redmi1")
declare -a results

for val in "${access_points[@]}"
do
    if ping -c 4 -w 10 "$val" 2>&1 >/dev/null
    then
       online="+"
    else
       online="-"
    fi
    results+=("$online")
done
echo "${results[@]}"
2
  • Can I start with access_points="tplink2 redmi1" somehow? Commented Dec 17, 2021 at 11:02
  • @Dims: You can, if the access points' names never contain whitespace. The loop will then have the form of for val in $access_points, i.e. no quotes. But why? Commented Dec 17, 2021 at 22:57

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.