Home > Net >  tee command wont work with file name in a variable
tee command wont work with file name in a variable

Time:11-26

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

CodePudding user response:

This works for me:

#!/bin/sh

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

It creates a file called file.txt with the contents in the script.


I found the answer here: https://stackoverflow.com/a/42086845/1766219

I'm not sure why you have the { and } in you code. If they are important, then please update your question with why you use them.

CodePudding user response:

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.

My assumption was wrong as per the comments bellow, the reason this doesn't work is due to the pipe command executing both sides as independent sub-processes therefore variables defined on one side do not exist on the other. Also on my suggestion bellow you might not want to use && if you don't care about the result of the first command.

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