quoting and escaping of a ssh command line

This question already has an answer here:

  • How to escape single quotes within single quoted strings? 19 answers

  • Here is a working solution by playing with the quotes:

    ssh -q rmthost "bash -c 'ps -ef|grep ''''<'defunct'>''''|grep -v grep|awk "'"{print $2}"'" '"
    

    however, I myself don't quite understand the mechanism :-). and it does't work if you swap single and double quotes.


    I'll be honest I can't read the code you've written. It's too obfuscated and I dont have half an hour to figure it out. To that end it's most likely not good code.

    Quotes like this get really very confusing when you try to understand the multiple layers of decoding. So instead of trying to correct your quotes I'm going to try to provde cleaner code with the same result.

    ssh rmthost "bash -c "ps -ef | grep '<defunct>' | grep -v grep | awk '{print $2}'""
    
    # The remote system will execute this:
    bash -c "ps -ef | grep '<defunct>' | grep -v grep | awk '{print $2}'"
    
    # Which in tells bash to execute this:
    
    ps -ef | grep '<defunct>' | grep -v grep | awk '{print $2}'
    

    However why not try to remove some exessive grep pipes. awk can do the filtering for you. I'm assuming that <defunct> appears at the end of the line. If so then you can just use:

    ssh rmthost "bash -c "ps -ef | awk '/<defunct>$/ {print $2}'""
    
    # the remote system executes this:
    bash -c "ps -ef | awk '/<defunct>$/ {print $2}'"
    
    # bash executes this:
    ps -ef | awk '/<defunct>$/ {print $2}'
    

    Or better still, use the second column in a ps -el which will be Z for zombie processes:

    ssh rmthost "bash -c "ps -el | awk '/^. Z / {print $4}'""
    
    # the remote system executes this
    bash -c "ps -el | awk '/^. Z / {print $4}'"
    
    # bash executes this:
    ps -el | awk '/^. Z / {print $4}'
    
    链接地址: http://www.djcxy.com/p/57134.html

    上一篇: 在linux bash中替换字符串

    下一篇: 引用和转义ssh命令行