LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   batch script help (https://www.linuxquestions.org/questions/linux-newbie-8/batch-script-help-4175412732/)

firebirdsql 06-21-2012 04:42 PM

batch script help
 
In my batch script, I want to check the output of a command and see if it contains a string and if so, run another command.

Basically, my wifi doesn't turn on sometimes during resume mode. I want to call the iwconfig command and check whether the output contains the string "Access Point" and if so run a command.

This is what I have so far:
Code:

#!/bin/bash
if [ `echo iwconfig || grep 'Access Point' `] then;
        ifdown wlan0;
        ifup wlan0;
fi;


suicidaleggroll 06-21-2012 04:54 PM

1 - You don't want to "echo iwconfig", because that will print the literal string "iwconfig" to the output, rather than actually running the program iwconfig
2 - You don't want double || between the iwconfig and the grep, double || is an "or" statement, if you want to grep the output of the iwconfig you would use a single |
3 - You can't run an if statement on this command anyway. If you run iwconfig | grep "Access Point", the result will either be "Access Point" or just a blank string, either way the if statement won't know what to do with it.
4 - You don't need a semicolon after each line

I would use the -q flag in grep, then check the exit status

Code:

#!/bin/bash
iwconfig | grep -q "Access Point"
if [[ $? -eq 0 ]]; then
  ifdown wlan0
  ifup wlan0
fi


firebirdsql 06-21-2012 05:10 PM

Nevermind, I was running the script by calling sh wifi instead of just wifi.

Thanks

suicidaleggroll 06-21-2012 05:11 PM

What distro is this?

You can try switching from double brackets to single:
Code:

#!/bin/bash
iwconfig | grep -q "Access Point"
if [ $? -eq 0 ]; then
  ifdown wlan0
  ifup wlan0
fi


David the H. 06-22-2012 02:03 PM

Actually, you don't need any test brackets at all, if statements operate on the exit code of whatever command (or command list) you supply after the initial keyword.

Code:

if iwconfig | grep -q "Access Point" ; then
        ifdown wlan0
        ifup wlan0
fi


More generally, however, when using bash or ksh, it's recommended to use [[..]] for string/file tests, and ((..)) for numerical tests. Avoid using the old [..] test unless you specifically need POSIX-style portability.

http://mywiki.wooledge.org/ArithmeticExpression
http://mywiki.wooledge.org/BashFAQ/031
http://wiki.bash-hackers.org/commands/classictest
http://wiki.bash-hackers.org/syntax/...nal_expression


All times are GMT -5. The time now is 09:43 PM.