Home > Mobile >  How to read command output and use it silently on a bash script?
How to read command output and use it silently on a bash script?

Time:12-11

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

CodePudding user response:

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

CodePudding user response:

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

  • Related