1

I'm new on bash. I want to write a script which will run iwconfig command the output should show me my wlan* mode is Managed or Monitor? I had tried this like following but it is not working and runs the command output. I just need to echo which mode is it.

IWCONFIG_LOG="$(iwconfig)"
if [[ "$IWCONFIG_LOG" == *Mode:Managed* ]]; then
  echo "Managed"
elif [[ "$IWCONFIG_LOG" == *Mode:Monitor* ]]; then
  echo "Monitor Mode"
fi
Learner
  • 11
  • 1
  • Please read [correct-bash-and-shell-script-variable-capitalization](https://stackoverflow.com/questions/673055/correct-bash-and-shell-script-variable-capitalization) – Ed Morton Dec 10 '21 at 14:52
  • Can you try with `=~` instead of `==` inside `if` conditions, like this: `if [[ "$IWCONFIG_LOG" =~ Mode:Managed ]]; then...` ? – User123 Dec 10 '21 at 15:00
  • I don't know how the standard output of iwconfig looks like, but the condition of your test does necessarily not look wrong to me. Doesn't `set -x` reveal anything? – user1934428 Dec 10 '21 at 16:05

2 Answers2

1

Looks like you want to use Bash (not sh) in order to get this accomplish. So, try this:

#!/bin/bash
IWCONFIG_LOG="$((iwconfig | grep Mode) 2> /dev/null)"
if [[ $IWCONFIG_LOG == *"Mode:Managed"* ]]; then
  echo "Managed"
elif [[ $IWCONFIG_LOG == *"Mode:Monitor"* ]]; then
  echo "Monitor Mode"
fi

Save it as a file and chmod 755 it to make it executable or execute it using "bash" instead "sh". There are several modes, not only Managed or Monitor, so seems you only want to detect one of these two. To see all available modes read man iwconfig

masterguru
  • 549
  • 4
  • 10
0

Since iwconfig writes also to standard error:

if [[ $(iwconfig 2>/dev/null | grep "Managed") ]]; then
    echo "Managed"
else
    echo "Monitor"
fi

or, as pointed out by @choroba in comments:

if iwconfig 2>/dev/null | grep -q Managed ; then
    echo "Managed"
else
    echo "Monitor"
fi
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
  • `if iwconfig 2>/dev/null | grep -q Managed ; then` – choroba Dec 10 '21 at 14:48
  • I dont have `iwconfig` to test with and couldn't find the answer to this in the man page but - are you sure the text the OPs interested in isn't part of what goes to stderr? If so, then `2>&1` would be required instead of `2>/dev/null`. – Ed Morton Dec 10 '21 at 14:56
  • Thanks. It's perfect. Now I am understanding some things. – Learner Dec 10 '21 at 14:59
  • I don't think this is a correct approach. What if iwconfig outputs neither "Managed" nor "Monitor" ? – M. Nejat Aydin Dec 10 '21 at 15:35