巴什 - 间preting一个变量的内容 [英] Bash - interpreting the contents of a variable

查看:179
本文介绍了巴什 - 间preting一个变量的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能让猛砸间preT变量的内容作为I / O重定向,而不​​是简单地传递这些内容正在执行的命令。就拿这个脚本,例如:

How can I make Bash interpret the contents of a variable as I/O redirects and not simply pass those contents to the command being executed. Take this script for example:

#!/bin/bash
test "$1" == '--log' && LOGGING="2>&1 | tee time.log" || LOGGING=""
date $LOGGING

所需的行为方式是,当我运行此脚本使用--log选项bash的西港岛线执行

The desired behavior is that when I run this script with the --log option bash wil execute

$日期2>&安培; 1 |三通time.log

$ date 2>&1 | tee time.log

如果我不指定--log那么它只是输出日期,而无需创建日志。相反,它把$测井的内容传送到日期导致错误一个CLI论点:

If I don't specify --log then it simply outputs date without creating a log. Instead it passes the contents of $LOGGING to date as a CLI argument resulting in an error:

 date: extra operand `|' Try `date
 --help' for more information.

有没有办法做到这一点,而无需编写像

Is there way to do this without writing something like

#!/bin/bash
test "$1" == '--log' && date 2>&1 | tee time.log || date

实际应用显然不仅仅是打电话要复杂得多约会,所以我想避免复制和粘贴,在一个命令两次,如果别人只追加重定向和日志记录命令。

The actual application is obviously much more complicated than just calling "date" so I'd like to avoid copying and pasting that command twice in an if else just to append the redirect and logging commands.

推荐答案

如果你的脚本是相当长的,你想记录所有输出和错误--log时传入,我建议使用exec来重定向一切。见这个优秀的文章:

If your script is rather long and you want to log all stdout and stderr when --log is passed in, I suggest using exec to redirect everything. See this excellent article:

http://www.linuxjournal.com/content/bash-redirections-使用-EXEC

#!/bin/bash
if [[ "$1" == '--log' ]]; then
    npipe=/tmp/$$.tmp
    trap "rm -f $npipe" EXIT
    mknod $npipe p
    tee <$npipe log &
    exec 1>&-
    exec 1>$npipe
fi

date
# and any other commands after this will be logged too.

这个方法的有​​趣的事情是,你也可以prePEND所有登录使用Perl或呆子或一些其他实用程序时间戳行:

The interesting thing about this approach is that you can also prepend all logged lines with a timestamp using perl or gawk or some other utility:

#!/bin/bash
if [[ "$1" == '--log' ]]; then
    npipe=/tmp/$$.tmp
    trap "rm -f $npipe" EXIT
    mknod $npipe p
    perl -pne 'print scalar(localtime()), " ";' < $npipe | tee time.log &
    exec 1>&-
    exec 1>$npipe 2>&1
fi

echo hello world
echo hello world 2

运行此之后,time.log将包含:

After running this, time.log will contain:

$ cat time.log 
Wed Jun  8 13:28:45 2011 hello world
Wed Jun  8 13:28:45 2011 hello world 2

这里的缺点在于,时间戳打印到终端太

The drawback here is that the timestamp are printed to your terminal too.

这篇关于巴什 - 间preting一个变量的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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