Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 789
comatose Avatar asked Jan 09 '13 13:01

comatose


2 Answers

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

like image 169
Lars Kotthoff Avatar answered Sep 21 '22 18:09

Lars Kotthoff


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"; }
like image 25
William Pursell Avatar answered Sep 21 '22 18:09

William Pursell