tee command wont work with file name in a variable

I am trying to output the contents of a bash script into a file, but when i put the file name into a variable, it does not work. But if I hardcode the same filename, it works.

I tried this

{
echo "in the script"
file='file.txt'
} | tee -a "$file"

however I get the error tee: : No such file or directory I also echo "$file" and I get back file.txt, so I know the variable is getting set correctly.
when I do:

{
echo "in the script"
} | tee -a "file.txt"

it creates the file and fills it no problem. Why isn’t my variable working here?

Edit: I am using brackets {} to encase my script because it is a rather large script that I want to output to a file. so echo "in the script" | tee -a "$file" will not work

>Solution :

I believe that when you use the brackets to group commands it creates a context, and if you define variables inside it they will only exist in that context, therefore not being passed to the command after the pipe.

You might want to do something like this instead ?

file="file.txt" && 
{
  echo "in the script"
} | tee -a "$file"

Leave a Reply