How to use bash $(awk) in single ssh-command?

后端 未结 6 553
没有蜡笔的小新
没有蜡笔的小新 2020-12-02 21:18

I am trying to execute a single command over ssh that contains `sub-code` or $(sub-code) (I use it all the time but I don\'t know the official name for that) to

相关标签:
6条回答
  • 2020-12-02 21:35

    What about piping the output of the command and run awk locally?

    ssh yourhost uname -a | awk '{ print $2 } '
    
    0 讨论(0)
  • 2020-12-02 21:39

    The workaround is to create an sh file with the command then pass it to ssh command:

    test.sh

    echo `uname -a | awk '{print $2}'`
    

    and command:

    ssh myServer 'bash -s' < test.sh
    

    UPDATE:

    The command without quotes works fine as well:

    ssh myServer uname -a | awk '{print $2}'
    
    0 讨论(0)
  • 2020-12-02 21:40

    If you are trying to get the hostname, use:

    ssh myServer "uname -n"

    0 讨论(0)
  • 2020-12-02 21:42

    It is better to use a heredoc with ssh to avoid escaping quotes everywhere in a more complex command:

    ssh -T myServer <<-'EOF'
    uname -a | awk '{print $2}'
    exit
    EOF
    
    0 讨论(0)
  • 2020-12-02 21:43

    Try this

    ssh myServer "uname -a | awk '{print \$2}' "
    

    Use the double quotes " in order to group the commands you will execute remotely.

    You also need to escape the $ in the $2 argument, so that it is not calculated locally, but passed on to awk remotely.

    Edit:

    If you want to include the $( ), you again have to escape the $ symbol, like this:

    ssh myServer "echo \$(uname -a | awk '{print \$2}') "
    

    You can also escape the backtick `, like this:

    ssh myServer "echo \`uname -a | awk '{print \$2}'\` "
    
    0 讨论(0)
  • 2020-12-02 21:46

    Just some additional note:

    In my case, the escape of the $ doesn't help:

    ts1350:> ssh sysadm@node "grep feature features.txt| awk '{print $6}' "
    Password: 
    A  feature   -name  ue_trace_mme    | off
    ts1350:> ssh sysadm@node "grep feature features.txt| awk '{print \$6}' "
    Password: 
    awk: cmd. line:1: {print \}
    awk: cmd. line:1:        ^ backslash not last character on line
    awk: cmd. line:1: {print \}
    awk: cmd. line:1:        ^ syntax error
    ts1350:> ssh sysadm@node "grep feature features.txt| awk '{print \\$6}' "
    Password: 
    awk: cmd. line:1: {print \\}
    awk: cmd. line:1:        ^ backslash not last character on line
    awk: cmd. line:1: {print \\}
    awk: cmd. line:1:        ^ syntax error
    

    While add a space between $ and the number works:

    Fri Oct  4 14:49:28 CEST 2019
    ts1350:> ssh sysadm@node "grep feature features.txt| awk '{print $ 6}' "
    Password: 
    off
    

    Hope this secodnary way help someone like me.

    Thanks to @dave in his answer: How to print a specific column with awk on a remote ssh session?

    0 讨论(0)
提交回复
热议问题