1

I need help with how to compare bash variable to a specific format.

i will read user input with read command

for example:
MyComputer:~/Home$ read interface
eth1
MyComputer:~/Home$ echo $interface
eth1

Now i need to check if "$interface" variable with IF loop(it should have "eth" in beginning and should contains numbers 0-9):

if [[ $interface=^eth[0-9] ]]
then
    echo "It looks like an interface name"
fi

Thanks in advance

3 Answers 3

3

You can use regular expressions for this:

if [[ $interface =~ ^eth[0-9]+$ ]]
then
  ...
fi
Sign up to request clarification or add additional context in comments.

2 Comments

I can understand ^ in if [[ $interface =~ ^eth[0-9]+$ ]] however could you please explain use of ~ and +$ in bash
This is regex. The =~ is the matching operator and + says that the stuff in the former [] should appear 1 or more times. I think the [[ ]] style isn't portable so one should avoid this?!
1

You can use bash's globs for this:

if [[ $interface = eth+([[:digit:]]) ]]; then
    echo "It looks like an interface name"
fi

(avoiding regexps removes one problem). Oh, and mind the spaces around the = sign, and also before and after [[ and ]].

Comments

0

You could use bash V3+ operator =~ as Andrew Logvinov said :

[[ $interface =~ ^eth[0-9]+$ ]] && # ...

Or :

if [[ $interface =~ ^eth[0-9]+$ ]]; then
    # ...
fi

Otherwise, you could use too egrep or grep -E (which is useful with older shells like sh...) :

echo "$interface"|egrep "^eth[0-9]+$" > /dev/null && # ...

Or :

if echo "$interface"|egrep "^eth[0-9]+$" > /dev/null; then
    # ...
fi

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.