1

i'm new at bash scripting and i am trying to write a script to check if an ethernet device is up and if so exit the script. That doesn't work as intended, maybe someone can give me a hint.

I start the script, then plug in my device and the script just seems to hang up in the terminal. It is not getting back to the command line.

When the device is plugged in already and the ethernet dev is up the script just runs perfectly. It then echoes 'Connected' and throws me back to command line.

#! /bin/sh
t1=$(ifconfig | grep -o enxca1aea4347b1)
t2='enxca1aea4347b1'
while [ "$t1" != "$t2" ];
do
    sleep 1;
done
echo "Connected"
exit 0
2
  • you can use the exit value of grep to decide if the loop should exit Commented Mar 7, 2016 at 21:51
  • thank you!!! now that you mention it i realise my error :D case closed Commented Mar 7, 2016 at 21:52

2 Answers 2

3

You don't even need to make the comparison; just check the exit status of grep.

t2='enxca1aea4347b1'
until ifconfig | grep -q "$t2"; do
    sleep 1;
done
echo "Connected"
exit 0

In fact, you don't even need grep:

until [[ "$(ifconfig)" =~ $t2 ]]; do
    sleep 1
done
Sign up to request clarification or add additional context in comments.

1 Comment

Note that [[ ]] is a bash extension, and not supported by all other shells. If you want to use this, change the shebang to #!/bin/bash or it may (or may not) fail.
2

You've made an infinite loop, since you're not updating the value of $t1 inside the while statement.

Instead, try:

#! /bin/sh
t1=$(ifconfig | grep -o enxca1aea4347b1)
t2='enxca1aea4347b1'
while [ "$t1" != "$t2" ];
do
    sleep 1;
    t1=$(ifconfig | grep -o enxca1aea4347b1)
done
echo "Connected"
exit 0

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.