Sometimes when writing a script you want to redirect the output of multiple commands to a file. This is useful when debugging or when you want to generate a file that is the result of multiple commands.

The naive approach is to redirect the output of each command to the file:

echo "Hello" > file.txt
echo "World" >> file.txt

There are several issues with this approach. You have to make sure that the first redirect is > and the following ones are >> otherwise you will overwrite the file when you meant to append to it. As you write and tune your script this is a very likely mistake to make. Also you have keep repeating the same file name which is also error prone though this can be mitigated by introducing a variable and using that instead. Another thing is that it’s not very efficient because the file is opened and closed multiple times. It’s also not atomic, meaning that if the file is accessed by another process the results are unpredictable.

Instead you can group the commands and redirect the output of the group:

{
  echo "Hello"
  echo "World"
} > file.txt