Yokai Yokai - 9 months ago 67
Linux Question

How to limit terminal output of a bash command in a script

I am creating a bash program that has many fully featured options as a networking program written in python. In my program, I am using the below command and it's specific output will be used as a variable.

I am looking for a command or method to display only specific terminal output of a command. For example if, in my script, I use the command:

iwconfig wlan0

Yet all I wish to see from this command is what mode in which wlan0 is set. (i.e. Master, Managed, Monitor, etc.)

I have looked and searched all over Google and Bash specific sites and cannot find a solution. I may be overlooking something.


The grep option you're looking for is -o, or --only-matching in its long form. It outputs only text that matches the search you gave it, and nothing else. For example:

iwconfig wlan0 | grep -o 'Mode:[^ ]*'

outputs Mode:Managed on my machine. The single quotes are necessary so that the shell won't try to interpret the [, ] and * characters (with double quotes, if you happened to have a file with precisely the wrong name in your current directory, the shell might wrongly expand your parameter to the name of that file). The regular expression inside the single quotes means "the text Mode:, followed by any number of non-space characters", which is exactly what you were looking for.