將 nmap 輸出分配給多個變數

將 nmap 輸出分配給多個變數

我正在使用 nmap 掃描我的網路並希望顯示每個已啟動的裝置。以下效果很好:

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

我現在想要的是將每個輸出保存在單獨的變數中。

假設ips給出這個輸出:

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

我現在想將(device1)保存在var1,(device2)中var2和(device3)中var3

我怎麼能這麼做呢?

答案1

ips[0]不要創建一堆單獨的標量變量,只需將命令輸出保存在數組中而不是標量變量中,然後您就可以以 、 等方式訪問ips[1]它。確切的命令輸出:printfnmap | awk

$ 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)")

https://stackoverflow.com/a/32931403/1745001有關上述將命令輸出保存在數組中的方法與其他方法的更多詳細資訊(readarray 和 mapfile 是同義詞)。

相關內容