2012-04-20 6 views
3

以下のように、スクリプト自体の中から標準エラーと標準出力をリダイレクトすることが可能である。代わりバッチ - バッチスクリプト自体からstderrとstdoutをどのようにリダイレクトできますか? Unixシェルスクリプトで

test.sh 

#!/bin/ksh 
# script_name: test.sh 
export AUTO_LOGFILE=`basename $0 .sh`.log 
# stdout and stderr Redirection. This will save the old stdout on FD 3, and the old stderr on FD 4. 
exec 3>&0 4>&1 >>$AUTO_LOGFILE 2>&1 
echo "Hello World" 
# The above echo will be printed to test.log 

は実際に、test.shを単に実行することができますof:

test.sh >> test.log 2>&1  

私は同様のバッチスクリプトを実行しようとしています。私のバッチコードは以下の通りです:

@echo off & setlocal enableextensions enabledelayedexpansion 
REM script_name=test.bat 
set AUTO_LOGFILE=%~n0.log 
REM How to do the stdout and stderr redirection from within the script itself here? 

バッチスクリプト自体からstderrとstdoutをリダイレクトする方法はありますか?

exec 3>&0 4>&1 >>$AUTO_LOGFILE 2>&1 
+0

あなたの質問はこれから重複しては:[それは、スクリプト内のバッチファイルの出力をリダイレクトすることは可能ですか?] [1] [1]:http://stackoverflow.com/questions/4607390/is-it-possible-the-output-of-output-of-a-batch-file-inside-the-script – Mac

+0

@Mac I多くのコマンドを実行し、スクリプトの後半部分で多くのサブルーチンを呼び出す必要があります。私はあなたが提供したリンクの答えに記載されているように、単に関数testitoutでそれを行うことはできません。 –

+0

これについてはわかりませんが、他のサブルーチンを呼び出すメインと同じように、サブルーチンがあった場合、それは機能しませんか? – Mac

答えて

5

TEST.BATバッチファイルは、以下の機能ある括弧内の行を囲みます。私は同等のバッチコードに、このUNIXシェルスクリプト文を変換して、より興味あなたのUnixスクリプトに相当するを出力します。つまり、すべての標準出力をログファイルに送信し、画面にエラー出力を出力します。

@echo off 
if defined reEntry goto reEntry 
set reEntry=TRUE 

set AUTO_LOGFILE=%~N0.log 
rem stdout Redirection. Leave stderr as is. 

"%~F0" %* >>%AUTO_LOGFILE% 

:reEntry 
set reEntry= 
echo "Hello World" 
rem The above echo will be printed to test.log 
rem and error messages will be printed to the screen: 
verify badparam 

Adenddeum:

私はOPは、画面にエラーメッセージを表示するために標準エラー出力から別の stdoutに望んでいると思ったが、おそらく私は彼を誤解。

"%~F0" %* >>%AUTO_LOGFILE% 2>&1 

か、すでに上記のコメントで提案しても簡単な方法で:

しかし
@echo off 
set AUTO_LOGFILE=%~N0.log 
rem stdout and stderr Redirection. 

call :Main %* >>%AUTO_LOGFILE% 2>&1 
goto :EOF 

:Main 
echo "Hello World" 
rem The above echo will be printed to test.log 

、dbenhamは彼のコメントで述べたように以下の行を使用して、ファイルにstdoutとstderrの両方を送信するには

"%~F0" %* 2>&1 1>&3 | findstr /N /A:4E "^" 
:目的は、通常の出力から distingishエラーメッセージである場合、それは、このトリックを介して同じ画面に を行うことができます

この方法では、エラーメッセージの前に赤色の背景に黄色の行番号が表示されます。この方法は、いくつかの場合に直接使用することができます。例えば、任意のプログラミング言語のソース・プログラムのコンパイルで:

anycompiler %1 2>&1 1>&3 | findstr /N /A:4E "^" 
+1

+1しかし、私はOPが同じファイルにリダイレクトしたいと思うので、 '"%〜F0 "%* >>%AUTO_LOGFILE%2>&1'です。また、Windowsはリダイレクトされたハンドルを最初に利用可能な未割り当てのハンドルに自動的に保存します。したがって、以前のリダイレクションが発生していない限り、元のstdoutはハンドル3に保存され、stderrはハンドル4に保存されます。 'echoこれはコンソール(stdout)に行きます>&3'はそれだけを行います。 – dbenham

1

(
    REM How to do the stdout redirection from within the script itself here? 
    ECHO is this redirected? 
    ECHO yes it is 
) >out.txt 
関連する問題