0

I need to get interface by number. My script:

#!/bin/bash

interfaces=/root/tt
interfaces_with_numbers=/root/tt2

ls -1 /sys/class/net > /root/tt
cat -n $interfaces > $interfaces_with_numbers
cat $interfaces_with_numbers

read number
echo $number

eth=`cat $interfaces_with_numbers | grep $number | awk '{ print $2 }'`

if [[ -d /sys/class/net/$eth ]];then
    echo "You choose is: $eth"
else
    echo "not found"
fi

I have output:

 1  dummy0
 2  eno1
 3  enp4s0
 4  lo
 5  virbr0
 6  virbr0-nic

It is simply text file with spaces. Ok. Script has asked, what i want to enter. I entered "2". It is working – In result, i get name of interface. I entered "1", and i have "not found". I have written in linux command line:

cat tt2 | grep 1 | awk '{ print $2 }'

And i have got the output:

dummy0
eno1

How to do this script correct ? Please help. Thanks for you attention.

2 Answers 2

1

Depending which interface you select, grep may be finding multiple answers. For example, selecting menu item #1 will cause grep to find both 1 dummy0 and 2 eno1. This results in two results being returned from grep which are separated by a newline character. eg:

eth='dummmy0 eno1'

when -d tries to evaluate eth, it tries to eval the entire variable, including the carriage return, and the statement obviously returns false. Try to use egrep with a regex for a fix. ^\s+$number will look only at the beginning of the line for a match. the \s+ will account for tabs or other whitespace prefixing the number:

eth=`cat $interfaces_with_numbers | egrep "^\s+$number" | awk '{ print $2 }'
0

You could use awk to check matching condition exactly:

eth=`awk "(\$1==$number) { print \$2 }" $interfaces_with_numbers`

You must log in to answer this question.

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