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 ?

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).

  • 1
    works perfectly, thank you! – crazydrazy Mar 19 '20 at 22:28
  • 1
    Super solution Thanks – Praveen Kumar BS Mar 22 '20 at 19:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.