How would you simplify this command?

I'm quite new to strace / netstat / etc. I'm using this command to get a trace of the apache process handling my request (telnet), is there a way to simplify it a bit?

sudo strace -o /tmp/strace -f -s4096 -r -p $(netstat -antlp | \ 
    grep $(lsof -p `pidof telnet` | grep TCP | \
    perl -n -e'/localhost:(\d+)/ && print $1') | grep apache2 | \ 
    perl -n -e'/ESTABLISHED (\d+)/ && print $1')

Thanks!


Solution 1:

I can improve on Mark Henderson's a little, with $() instead of `` and removing the grep with a better sed:

sudo strace -o /tmp/strace -f -s4096 -r -p $(netstat -antlp | \
   sed -e "/telnet/s/^.*ESTABLISHED\ \|\/.*$//g")

Personally I think the backticks make it difficult to read; furthermore, they don't nest, unlike the $() syntax

Solution 2:

strace -p $(ss -npt|sed -n "/:$(ss -npt|sed -n '/telnet/s/^.*\?:\([0-9]\+\).*/\1/p') \+u/s/.*,\(.*\),.*/\1/p")

As long as you only have one telnet running, this will strace the corresponding server if any.

If there isn't one (eg you telneted to an external server last), strace will fail with strace: option requires an argument -- 'p'