英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论