Quantcast
Channel: Debian User Forums
Viewing all articles
Browse latest Browse all 2901

Docs, HowTos, Tips & Tricks • Re: [Challenge] Q1. Process/Port location and kill

$
0
0
I realize I should have explained the command a bit.

Code:

myCMD="nc"                 ### assign the value "nc" to the myCMD variabledeclare -i CMDport=34567   ### declare the CMDport variable as integer and assign it the value 34567mawk -v cmd="$myCMD" -v port=$CMDport '{if ($1==cmd && $NF~":"port"$"){print $2 >"/dev/stdout"; print $0 >"/dev/stderr"}}' < <(lsof -Tf -i:$CMDport) | xargs kill -15
mawk is an interpreter for the AWK Programming Language.
AWK is a domain-specific language designed for text processing and typically used as a data extraction and reporting tool.
[...]
The language extensively uses [...] regular expressions.
-v cmd="$myCMD" -v port=$CMDport imports shell variables into mawk.
if (condition) {action} the basic structure of an AWK program.
$1 mawk splits the line into fields separated by spaces. $1 is the first field, $2 the second, $NF (Number of Fields) the last, $0 is the entire line.
== relational equality operator, evaluates literally (does not interpret regular expressions)
~ matching (interprets regular expressions)
&& logical and
":"port"$" variables are outside the quotes. $ is a regular expression which means at the end of the expression, so here a line which ends with :34567
print $2 >"/dev/stdout" prints the second field, redirected to standard output. Since standard output is the default, >"/dev/stdout" could have been omitted.
print $0 >"/dev/stderr" prints the entire line to standard error. Unlike stdout which is redirected to the next program through the pipe (|), stderr is echoed to the terminal.

< <(lsof -Tf -i:$CMDport) this process substitution redirects the command output to mawk. In this case, it is an equivalent to the following pipe.

Statistics: Posted by fabien — 2024-05-17 23:52



Viewing all articles
Browse latest Browse all 2901

Trending Articles