2012-08-22 48 views
3

我正在尋找一個解決方案(類似於下面的bash代碼)將stdout和stderr複製到除了ksh在Solaris中的屏幕之外的文件。將stderr和stdout複製到文件以及ksh中的屏幕

下面的代碼在bash shell中的偉大工程:

#!/usr/bin/bash 

# Clear the logfile 
>logfile.txt 

# Redirect all script output to a logfile as well as their normal locations 
exec > >(tee -a logfile.txt) 
exec 2> >(tee -a logfile.txt >&2) 
date 
ls -l /non-existent/path 

出於某種原因,這是扔在Solaris語法錯誤。我認爲這是因爲我不能進行流程替換,並且我看到一些帖子提示使用mkfifo,但我還沒有想出一個可行的解決方案。

有誰知道一種方式,除了默認位置之外,所有輸出都可以重定向到文件嗎?

回答

3

您正在使用哪個版本的ksh?在ksh88中不支持>(),但在ksh93中受支持 - bsh代碼在ksh93上應該保持不變(除#!行之外)。

如果你被卡住ksh88(真可憐!),那麼你可以使用命名管道效仿在bash/ksh93的行爲:

#!/bin/ksh 
# Clear the logfile 
>logfile.txt 

pipe1="/tmp/mypipe1.$$" 
pipe2="/tmp/mypipe2.$$" 
trap 'rm "$pipe1" "$pipe2"' EXIT 
mkfifo "$pipe1" 
mkfifo "$pipe2" 
tee -a logfile.txt < "$pipe1" & 
tee -a logfile.txt >&2 < "$pipe2" & 

# Redirect all script output to a logfile as well as their normal locations 
exec >"$pipe1" 
exec 2>"$pipe2" 

date 
ls -l /non-existent/path 

上面是第二個版本,以使標準錯誤重定向到一個不同的文件。

+0

這幾乎是我所需要的,但是這不會將STDOUT和STDERR文件描述符分開。如果我像'./script.sh> out.log 2> err.log'那樣調用腳本,那麼所有的輸出都會輸出到out.log,但是有些應該到err.log – HuggieRich

+0

好,所以你需要另一個'tee '和管道 - 修改原來的答案... – cdarke

+0

它排序,非常好。 – HuggieRich

2

如何:

(some commands ...) 2>&1 | tee logfile.txt 

添加-atee命令行的後續調用追加而不是覆蓋。

+0

我不希望有對每一個指令做到這一點,理想情況下,我喜歡的東西,我可以把在腳本的頂部就像上面的例子一樣。 – HuggieRich

+0

我還應該提到它必須在腳本內完成。我有一個運行腳本的守護進程,它捕獲所有輸出到日誌文件,所以我無法控制命令行上的調用。 – HuggieRich

1

KSH中,以下工作對我非常好

LOG=log_file.$(date +%Y%m%d%H%M%S).txt 
{ 
ls 
date 
... whatever command 
} 2>&1 | tee -a $LOG 
相關問題