如何从csh脚本重定向stdout和stderr

9
以下是脚本的翻译内容:

install.csh:

#!/bin/csh -f
tar -zxf Python-3.1.1.tgz
cd Python-3.1.1
./configure
make
make install
cd ..
rm -rf Python-3.1.1

预期用途:

./install.csh |& tee install.log

如何更改脚本,以便我仍然可以在控制台上获得install.log和输出,而无需要求用户进行重定向?

3个回答

6

一些简单的解决方案:

解决方案1: 独立记录每行要记录的内容,利用tee命令的-a选项进行追加。

#!/bin/csh -f    
tar -zxf Python-3.1.1.tgz |& tee -a install.log
cd Python-3.1.1 |& tee -a install.log
./configure |& tee -a install.log
make |& tee -a install.log
make install |& tee -a install.log
cd .. |& tee -a install.log
rm -rf Python-3.1.1 |& tee -a install.log

解决方案2:添加第二个脚本。 例如,将当前的install.csh重命名为install_commands, 然后添加一个新的install.csh脚本:
#!/bin/csh -f 
/bin/csh install_commands |& tee install.log

谢谢。我在想可能有其他我不知道的技巧,可以导致一个优美的解决方案。 - Shelly Adhikari
哦,将其拆分为两个脚本是个好主意。+1 但我仍然认为你不应该坚持使用csh!(-: - Rob Wells

3

你好,

强烈建议从csh转向像bash或zsh这样的东西。

在csh中不可能进行stdio操作。请阅读"csh编程被认为是有害的"。这是关于这个主题的优雅论文。

很抱歉这不是一个直接的答案,但你会发现如果你坚持使用它,你会越来越受到csh的限制而头疼不已。

许多csh语法在bash中已经可用,因此您的学习曲线不会太陡峭。

以下是用bash编写相同内容的快速建议。虽然不太优雅。

#!/bin/bash
TO_LOGFILE= "| tee -a ./install.log"
tar -zxf Python-3.1.1.tgz 2>&1 ${TO_LOGFILE}
if [ $? -ne 0 ];then
    echo "Untar of Python failed. Exiting..."; exit 5
fi

cd Python-3.1.1 2>&1 ${TO_LOGFILE}
if [ $? -ne 0 ];then
    echo "Can't change into Python dir. Exiting..."; exit 5
fi
echo "============== configure ================"
./configure 2>&1 ${TO_LOGFILE}
if [ $? -ne 0 ];then
    echo "Configure failed. Exiting..."; exit 5
fi
echo "================ make ==================="
make 2>&1 ${TO_LOGFILE}
if [ $? -ne 0 ];then
    echo "Compile of Python failed. Exiting..."; exit 5
fi
echo "================ install ================"
make install 2>&1 ${TO_LOGFILE}
if [ $? -ne 0 ];then
    echo "Install of Python failed. Exiting..."; exit 5
fi

cd ..
rm -rf Python-3.1.1 2>&1 ${TO_LOGFILE}
exit 0

我已经增加了更多的检查和报告,以便如果在较早的步骤中出现问题,日志文件将只包含直到错误被发现的部分,而不是一堆无用的来自后期阶段的错误消息,这些消息本来也无法完成。

谢谢!


@Shelly,抱歉。我忘记你想要复制到控制台了。 - Rob Wells

0

您可以在子shell中运行它并将所有输出重定向到那里。我不记得这在csh中是否有效,因为我已经很久很久没有使用了。

#!/bin/csh -f
(
tar -zxf Python-3.1.1.tgz
cd Python-3.1.1
./configure
make
make install
cd ..
rm -rf Python-3.1.1
) |& tee install.log

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接