Search code examples
linuxbashvariableshttp-redirectscp

capturing text from scp to variable or array


I'm trying to capture the output of an scp command to a variable or array in Bash. I'm not exactly sure where the text comes from local or remote ?

So far I've tried the following :

#!/bin/bash -x 

mytty=$(tty)
echo "mytty is ${mytty}"
myvar=$(scp  test.js  crashdog@webserver.com:/home/crashdog 2>&1 > $mytty)
echo "myvar is ${myvar}"

I can see the text on my tty like follows:

test.js                                                                                                 100% 1200     1.2KB/s   00:00 

But myvar remains empty. So my two questions, where is above text coming from ? and how can I assign the text to a variable or array in Bash.

Thanks


Solution

  • Your problem is that scp doesn't output anything when its stdout isn't the terminal.

    To trick it you can use script:

    out=$(script -qefc "scp test.js crashdog@webserver.com:/home/crashdog" /dev/null)
    
    echo "$out"
    

    You can find more info about it in How to trick an application into thinking its stdout is a terminal, not a pipe