×
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Contact US

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

BASH script - array problem

BASH script - array problem

BASH script - array problem

(OP)
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

RE: BASH script - array problem

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.

CODE --> 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

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close