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

旧巷老猫 提交于 2019-12-05 03:02:23

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

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"; }
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

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!