Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

Initialize the variable before setting up the redirection:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading