How to use a variable from a block of code in the filename the output is redirected to?

huangapple go评论64阅读模式
英文:

How to use a variable from a block of code in the filename the output is redirected to?

问题

I have a shell script of which I want to capture the output using a block of code (docs).

Additionally I want to use the value of a variable from that block of code in the filename I write the output to, unfortunately that is not working.

How can I re-use the variable from a block of code in the filename?

最小示例

这是一个虚拟脚本,展示了我想要做的事情。我使用的是 GNU bash, version 5.0.17

{
    v=1
    echo $v
} >> output-$v.log 2>&1

我设置了一个变量,运行一些命令,并希望将stdout和stderr存储在一个带有该变量的名称的文件中(在这种情况下是 output-1.log)。

然而,这会写出一个名为 output-.log 的文件,就好像 $v 变量不存在一样。

我尝试过的事情

如果我在代码块后面添加一个分号 ;

{
    v=1
    echo $v
}; >> output-$v.log 2>&1

则会创建文件 output-1.log,但它保持为空。

英文:

I have a shell script of which I want to capture the output using a block of code (docs).

Additionally I want to use the value of a variable from that block of code in the filename I write the output to, unfortunately that is not working.

How can I re-use the variable from a block of code in the filename?

Minimum example

This is a dummy script showing what I'm trying to do. I have GNU bash, version 5.0.17:

{
    v=1
    echo $v
} >> output-$v.log 2>&1

I set a variable, run some command and want to store the stdout and stderr in a file that has the variable in it's name (output-1.log in this case).

However, this writes out a file output-.log as if the $v variable does not exist.

What I've tried

If I add a semicolon ; after the block of code:

{
    v=1
    echo $v
}; >> output-$v.log 2>&1

The file output-1.log is created, but it remains empty

答案1

得分: 1

初始化变量后设置重定向:

v=1
{
  echo $v
} >> output-$v.log 2>&1
英文:

Initialize the variable before setting up the redirection:

v=1
{
  echo $v
} >> output-$v.log 2>&1

huangapple
  • 本文由 发表于 2023年5月17日 22:23:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76273161.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定