Query on executing awk using SSH

Hi All,

Im trying to find the count of process running on remote server using SSH.

Below command dosen't work.


ssh -q user@host "ps -ef | grep "pattern" | grep -v 'grep' | awk '{print $2}'|wc -l"

But below command works.


ssh -q user@host "ps -ef | grep "pattern" | grep -v 'grep' | awk '{print \$2}'|wc -l"

the difference between 2 commands is $ was eacaped in second command.

Can any one explain the concept why we should escape $.

Because the command string is enclosed in double quotes and so the shell will try to expand variable $2 , therefore the $-sign needs to be escaped..

There are two sections protected by double quotes:

"ps -ef | grep "

and

" | grep -v 'grep' | awk '{print \$2}'|wc -l"

To join them into one section protected by double quotes, you would need to also escape the double quotes within the double quotes.. ...grep \"pattern\"...