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

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:

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

{
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"
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