Bash redirect and add to nonexistent file / directory

When i use >> nonexistent/file.log. Bash returns to me "There is no such file or directory."

How can I create one liner that redirects STDOUT / STDERR to a log file, even if it does not exist? If it does not exist, it must create the necessary folders and files.

+4
source share
4 answers

Usage install:

command | install -D /dev/stdin nonexistent/file.log

or use

mkdir nonexistent

the first.

+10
source

You can use dirnameto get the base path to the file and then use it with mkdir -p. After that, you can redirect:

sh mkdir -p `dirname nonexistent/file.log` echo blah >> nonexistent/file.log

+3
source

, , , , ( , )

if [ ! -d ~/nonexistent ]
  then mkdir ~/nonexistent
fi

Then use the other examples provided to simply copy the resulting file created with ls, back to the host field in the newly created directory.

+2
source

To automatically generate all directories for a file path:

FILEPATH="/folder1/folder2/myfile.txt"
if [ ! -f "$FILEPATH" ]; then
    mkdir -p "$FILEPATH"
    rm -r "$FILEPATH"
fi
#/folder1/folder2 has now been created.
0
source

All Articles