Bash,stdout重定向(如scp的命令) [英] Bash, stdout redirect of commands like scp

查看:87
本文介绍了Bash,stdout重定向(如scp的命令)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个bash脚本,其中包含一些scp命令.它工作得很好,但是,如果我尝试使用" ./myscript.sh> log "重定向我的标准输出,则"log"文件中仅显示我的显式回声.scp输出丢失.

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

推荐答案

scp 使用交互式终端以打印该精美的进度条.将输出打印到文件根本没有意义,因此 scp 会检测何时将其输出重定向到终端以外的其他位置,并禁用此输出.

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.

有两种可能的方法.首先是通过将stderr和stdout重定向到日志文件来调用脚本:

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

第二,是告诉bash在脚本中正确执行此操作:

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

...

如果需要检查错误,只需在执行scp命令后确认 $? 0 :

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

另一种选择是在脚本中执行 set -e ,该命令告诉bash脚本一旦脚本中的命令之一失败就报告失败:

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!

这篇关于Bash,stdout重定向(如scp的命令)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆