1

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

Saaru Lindestøkke
  • 2,067
  • 1
  • 25
  • 51
  • The redirection must be set up by the shell before the program is run. Therefore you need to set `v` in a previous statement, outside of your code block. – user1934428 May 17 '23 at 14:26
  • Thanks! If I move `v=1` before the block of code it works. If the redirection is set-up before the program, why does the variable propagate to the filename correctly when I run it with the semicolon (ignoring for a moment that the file remains empty)? – Saaru Lindestøkke May 17 '23 at 14:34
  • It does not. The semicolon terminates the code block (which is simply not redirected), and then you have an empty command consisting only of redirection. `; >output-1.log` creates an empty logfile. – user1934428 May 17 '23 at 14:38
  • Alright, I see. Thanks again! Feel free to make your first comment an answer so I can accept it. – Saaru Lindestøkke May 17 '23 at 14:42

1 Answers1

1

Initialize the variable before setting up the redirection:

v=1
{
  echo $v
} >> output-$v.log 2>&1
user1934428
  • 19,864
  • 7
  • 42
  • 87