Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

BASH script - array problem 1

Status
Not open for further replies.
I'm trying to write a script which captures all the available WiFi SSIDs in my area, then puts them into an array 'a'. I don't get an error, however, when I print the size of my array at the end of the script I get 0. I'm sure I've got my array syntax wrong, but cannot figure out what to change.


Code:
#!/bin/bash

a=()
n=0
sudo iwlist wlan0 scan |grep ESSID |grep -v '""' |sed 's/ESSID://' |sort |uniq |while read line; do
   echo "$n $line"
   a[$n]="$line"
   n=$((n+1))
   done
echo

echo ${#a[@]}


0 "NETGEAR03"
1 "Scott_Guest"
2 "Spyglass 2"
3 "TELUS0527"
4 "TELUS5D4C"
5 "wino911"

0
 
Hi

Your array syntax is correct. You only missed the fact that when input is piped to a loop, it runs as a subprocess. So what you set inside the loop will be unavailable once the loop ends and the subprocess terminates. Either avoid piping or use another shell in which piping does not turn the loop into subprocess, for example Zsh.
Bash:
#!/bin/bash

a=()
n=0
while read line; do
   echo "$n $line"
   a[$n]="$line"
   n=$((n+1))
done
echo <<< "$( sudo iwlist wlan0 scan |grep ESSID |grep -v '""' |sed 's/ESSID://' |sort |uniq )"

echo ${#a[@]}


Feherke.
feherke.github.io
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top