Capturing SSH output as variable in bash script

前端 未结 2 941
北荒
北荒 2020-12-28 16:21

I\'ve been struggling with this problem when writing a bash script. Basically, I want to measure the time of a program on a remote server, so I use the command: /usr/b

相关标签:
2条回答
  • 2020-12-28 16:40

    Try swapping the order of your redirections around (to 2>&1 >/dev/null). Your current code is sending both stdout and stderr to /dev/null (so I'm kind of curious as to why anything is printed at all).

    Why is this necessary? The syntax 2>&1 means 'duplicate stdout (descriptor 1) as stderr (descriptor 2)'; in effect, stderr is made into a copy of the current stdout. If you put >/dev/null first, then stdout is first redirected to /dev/null, and then stderr is pointed at the current stdout, i.e. /dev/null.

    But if you put >/dev/null second, stderr will first become a copy of the current stdout (the normal output stream), before stdout is redirected. So the command's stderr prints to the tty (or the interpreter) as if it came from stdout, while stdout is silenced. This is the behaviour you want.

    From man bash:

    Note that the order of redirections is significant. For example, the command

    ls > dirlist 2>&1
    

    directs both standard output and standard error to the file dirlist, while the command

    ls 2>&1 > dirlist
    

    directs only the standard output to file dirlist, because the standard error was duplicated as standard output before the standard output was redirected to dirlist.

    0 讨论(0)
  • 2020-12-28 16:59

    "time" command prints result to stderr, not to stdout. Thus it is not piped into your variable.

    You should reroute stderr to stdout to achieve what you want:

     result=$(ssh host time "command" 2>&1)
    

    And your full code can look something like this:

     respond=$(ssh ${fromNode} /usr/bin/time "-f" "%e" "'sh' '-c' 'virsh migrate --live ${VM} qemu+ssh://${toNode}/system > /dev/null 2>&1'" 2>&1)
    
    0 讨论(0)
提交回复
热议问题