use tee command to redirect output to a file in a non-existent dir
Asked Answered
I

4

19

I am trying to use the tee command to redirect output to a file, and I want the file to be created in a dir which is yet to be created.

date | tee new_dir/new_file

when new_dir is not there, the tee command fails saying

tee: new_dir/new_file: No such file or directory

If I create the new_dir prior to running the tee command, then it works fine, but for some reason I don't want to create the new_dir manually, is it possible to create the new_dir with the tee command ?

Internuncial answered 9/1, 2013 at 13:46 Comment(0)
Q
32

No. You'll have to create the directory before running tee.

Quartered answered 9/1, 2013 at 13:53 Comment(1)
The directory already exists in my case, but tee complains that the file does not exist, if I do not use the -a flag with tee.Fidele
M
10

Replace tee with a function that creates the directory for you:

tee() { mkdir -p ${1%/*} && command tee "$@"; }

If you want the function to work when invoked with a simple file name:

tee() { if test "$1" != "${1%/*}"; then mkdir -p ${1%/*}; fi &&
   command tee "$1"; }
Margarito answered 9/1, 2013 at 13:57 Comment(1)
tee foo.txt => mkdir -p foo.txt && command tee "foo.txt" I don't think that's quite right...Temperature
B
2
mkdir ./new_dir && date | tee ./new_dir/new_file

Since it is tee command, it simultaneously writes both to the new_file and to stdout

Butterbur answered 9/1, 2013 at 14:2 Comment(0)
E
0

Hmm... After some experiments, I've found some interesting things.

First of all, let's try to touch some file:

touch ~/.lein/profiles.clj

It works fine. But let's use the same thing with quotes:

touch "~/.lein/profiles.clj" # => touch: cannot touch ‘~/.lein/profiles.clj’: No such file or directory

So, for my bash function:

append_to_file() {
  echo $2 | tee -a $1
}

after that I changed call from it:

append_to_file '~/.lein/projects.clj' '{:user {:plugins [[lein-exec "0.3.1"]]}}'

to it (first argument without quotes):

append_to_file ~/.lein/projects.clj '{:users {:plugins [[lein-exec "0.3.1"]]}}'

And all is well.

UPDATE

This case considers .lein as existing directory.

Encipher answered 5/9, 2013 at 18:33 Comment(1)
touch "~/.lein/profiles.clj" fails because double quotes inhibit tilde-expansion.Temperature

© 2022 - 2024 — McMap. All rights reserved.