Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash redirect and append to non-existent file/directory

Tags:

redirect

bash

When I use >> nonexistent/file.log. Bash gives me back "No such file or directory".

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

like image 298
CMCDragonkai Avatar asked Jan 10 '14 19:01

CMCDragonkai


People also ask

How do you redirect the output of a command to a file without overwriting the contents of an existing file in Linux?

The append >> operator adds the output to the existing content instead of overwriting it. This allows you to redirect the output from multiple commands to a single file. For example, I could redirect the output of date by using the > operator and then redirect hostname and uname -r to the specifications.


2 Answers

Using install :

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

or use

mkdir nonexistent

first.

like image 129
Gilles Quenot Avatar answered Sep 30 '22 17:09

Gilles Quenot


You can use dirname to get the base path of the file, and later use it with mkdir -p. After that you can do the redirection:

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

like image 27
Piranna Avatar answered Sep 30 '22 15:09

Piranna