用变量缩短命令

时间:2017-04-15 23:15:51

标签: bash shell

我经常使用以下命令(实际路径较长):

>>/root/error.log 2>&1 >>/root/out.log

但现在我正试图缩短它:

log="$(>>/root/error.log 2>&1 >>/root/out.log)"

但是当我在另一个文件中使用该变量时,它根本不起作用:

apt-get update -y ${log}

你有什么想法,如何让这个工作?



修改 目前命令看起来像这样:

apt-get update -y >>/root/error.log 2>&1 >>/root/out.log

apt-get install openssl >>/root/error.log 2>&1 >>/root/out.log

......并且工作正常。但我想要一个更短的版本,如:

apt-get update -y ${log} 

apt-get install openssl ${log}

例如

1 个答案:

答案 0 :(得分:2)

您要封装的内容不是命令。它是您要执行的命令的重定向部分。

这不起作用。您可以在重定向中使用变量中的文件名,但不能包含>>>&1部分。

最简单的解决方案是创建一个函数。

execute_and_log()
{
  "$@" >>/root/out.log 2>>/root/error.log
}

execute_and_log any_command with args

请注意"$@"(双引号在这里非常重要)扩展为当前上下文中所有位置参数的列表(可能根本没有参数,可以扩展为空),每个参数都是防止进一步的单词拆分,就像调用"$1" "$2" ...

一样

请注意eval可用于在执行扩展后执行命令,但虽然它可以正常使用,但它很棘手,应该被视为最后的手段,因为通常更简单,不易出错的解决方案。

另一种可能性是:

main_log="long/path/to/file1"
err_log="long/path/to/file2"
apt-get update -y >>"$main_log" 2>>"$err_log"