views:

55

answers:

1

Hi, I have a bash script with some scp commands inside. It works very well but, if I try to redirect my stdout with "./myscript.sh >log", only my explicit echos are shown in the "log" file. The scp output is missing.

if $C_SFTP; then
   scp -r $C_SFTP_USER@$C_SFTP_HOST:$C_SOURCE "$C_TMPDIR"
fi

Ok, what should I do now? Thank you

+1  A: 

scp is using interactive terminal in order to print that fancy progress bar. Printing that output to a file does not make sense at all, so scp detects when its output is redirected to somewhere else other than a terminal and does disable this output.

What makes sense, however, is redirect its error output into the file in case there are errors. You might want to disable standard output if you want.

There are two possible ways of doing this. First is to invoke your script with redirection of both stderr and stdout into the log file:

./myscript.sh >log 2>&1

Second, is to tell bash to do this right in your script:

#!/bin/sh

exec 2>&1

if $C_SFTP; then
   scp -r $C_SFTP_USER@$C_SFTP_HOST:$C_SOURCE "$C_TMPDIR"
fi

...

If you need to check for errors, just verify that $? is 0 after scp command is executed:

if $C_SFTP; then
   scp -r $C_SFTP_USER@$C_SFTP_HOST:$C_SOURCE "$C_TMPDIR"
   RET=$?
   if [ $RET -ne 0 ]; then
      echo SOS 2>&1
      exit $RET
   fi
fi

Another option is to do set -e in your script which tells bash script to report failure as soon as one of commands in scripts fails:

#!/bin/bash

set -e

...

Hope it helps. Good luck!

Vlad Lazarenko
`if [ "$RET" -ne "0" ]; then..` there is no need for " around 0, `-ne/-eq` will test integer values.
Anders
@Anders: Just a habit. Changed that.
Vlad Lazarenko