Read and assign value to the result of a command

3

I have the following script

nmap_result=$(sudo nmap -sP 192.168.0.1/24)
own_ip=$(ifconfig wlp2s0b1 | grep inet | awk '{print $2}' | cut -d':' -f2)
temp_mac=$(echo "$nmap_result" | grep "MAC Address:" | awk '{print $3;}') 
temp_ip=$(echo "$nmap_result" | grep "192.168." | awk '{print $5;}' | grep -v "$own_ip")
temp_vendor=$(echo "$nmap_result" | grep "MAC Address:" | awk '{print $4;}')
readarray -t mac <<<"$temp_mac"
readarray -t ip <<<"$temp_ip"
readarray -t vendor <<<"$temp_vendor"
len=${#mac[@]}
for (( i=0; i<${len}; i++ ));
do
echo ${vendor[i]}": "${ip[i]}" - "${mac[i]}
done

that when executing it gives me for example the following result

(Hon: 192.168.0.1 - 9x:Dx:1x:6x:Bx:Dx
(Mot: 192.168.0.5 - Ex:9x:2x:Dx:8x:Fx
(LG: 192.168.0.7 - Ax:9x:6x:Fx:Fx:Cx
(TCT: 192.168.0.8 - Bx:4x:1x:Ax:Cx:5x
(LG: 192.168.0.11 - Cx:9x:0x:5x:0x:Cx

There is some way to number and assign a value to each of the ip

for example

1. (Hon: 192.168.0.1 - 9x:Dx:1x:6x:Bx:Dx
2. (Mot: 192.168.0.5 - Ex:9x:2x:Dx:8x:Fx
3. (LG: 192.168.0.7 - Ax:9x:6x:Fx:Fx:Cx
4. (TCT: 192.168.0.8 - Bx:4x:1x:Ax:Cx:5x
5. (LG: 192.168.0.11 - Cx:9x:0x:5x:0x:Cx

and thus make a selection menu and when selecting a number to make a certain action

I hope to have explained to me

    
asked by Gabriel Caltzontzi suarez 13.04.2016 в 00:56
source

1 answer

3

From the moment you are using a loop, use the variable!

for (( i=0; i<${len}; i++ )); do
   printf "%d. %s: %s - %s\n" $((i+1)) "${vendor[i]}" "${ip[i]}" "${mac[i]}"
done

Notice that I use printf to have more control over what I write.

Note that your code is very optimizable, for example you say:

temp_mac=$(echo "$nmap_result" | grep "MAC Address:" | awk '{print $3;}') 

when a simple awk would already solve it:

temp_mac=$(awk '/MAC Address:/ {print $3}' <<< "$nmap_result") 
    
answered by 13.04.2016 в 13:36