0

I am using nmap to scan my network and want to show every device that is up. The following works great:

ips=$(nmap -sn 192.168.1.68/24 -oG - | awk '/Up$/{print $2, $3}')

What I now want to to is to save every output in a seperate variable.

Lets say ips give this output:

$ echo "$ips"
xxx.xxx.x.1 (device1)
xxx.xxx.x.2 (device2)
xxx.xxx.x.3 (device3)

I now want to save (device1) in var1,(device2) in var2 and (device3) in var3

How could I do that ?

0

1 Answer 1

1

Don't create a bunch of separate scalar variables, just save the command output in an array instead of a scalar variable and then you'll be able to access it as ips[0], ips[1], etc. Using printf instead of your current nmap | awk pipeline for simplicity to reproduce your exact command output:

$ printf 'xxx.xxx.x.1 (device1)\nxxx.xxx.x.2 (device2)\nxxx.xxx.x.3 (device3)\n'
xxx.xxx.x.1 (device1)
xxx.xxx.x.2 (device2)
xxx.xxx.x.3 (device3)

$ ips=$(printf 'xxx.xxx.x.1 (device1)\nxxx.xxx.x.2 (device2)\nxxx.xxx.x.3 (device3)\n')

$ echo "$ips"
xxx.xxx.x.1 (device1)
xxx.xxx.x.2 (device2)
xxx.xxx.x.3 (device3)

$ readarray -t -d $'\n' ips < <(printf 'xxx.xxx.x.1 (device1)\nxxx.xxx.x.2 (device2)\nxxx.xxx.x.3 (device3)\n')

$ declare -p ips
declare -a ips=([0]="xxx.xxx.x.1 (device1)" [1]="xxx.xxx.x.2 (device2)" [2]="xxx.xxx.x.3 (device3)")

See https://stackoverflow.com/a/32931403/1745001 for more details on the above approach to saving command output in an array vs other approaches (readarray and mapfile are synonyms).

2
  • 1
    works perfectly, thank you!
    – crazydrazy
    Mar 19, 2020 at 22:28
  • 1
    Super solution Thanks Mar 22, 2020 at 19:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .