gpt4 book ai didi

Bash - 解释变量的内容

转载 作者:行者123 更新时间:2023-11-29 09:49:25 25 4
gpt4 key购买 nike

如何让 Bash 在 I/O 重定向时解释变量的内容,而不是简单地将这些内容传递给正在执行的命令。以这个脚本为例:

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

期望的行为是,当我使用 --log 选项运行此脚本时,bash 将执行

$ 日期 2>&1 |开球时间.log

如果我不指定 --log 那么它只是输出日期而不创建日志。相反,它将 $LOGGING 的内容作为 CLI 参数传递到最新,导致错误:

 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

实际的应用程序显然比仅仅调用“日期”要复杂得多,所以我想避免在 if else 中复制和粘贴该命令两次,只是为了附加重定向和日志记录命令。

最佳答案

如果您的脚本相当长并且您想在传入 --log 时记录所有标准输出和标准错误,我建议使用 exec 来重定向所有内容。请参阅这篇优秀文章:

http://www.linuxjournal.com/content/bash-redirections-using-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.

这种方法的有趣之处在于,您还可以使用 perl 或 gawk 或其他一些实用程序在所有记录的行前加上时间戳:

#!/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 将包含:

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

这里的缺点是时间戳也会打印到您的终端。

关于Bash - 解释变量的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6284019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com