Bash redirect and append to non-existent file/directory

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


If this is run multiple times, and only the first time will the directory be missing, might want to check for it first (before you start your expect stuff)

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

Then use the other examples posted to simply scp the resulting file you create with ls back to your host box in the newly created directory.


Using install :

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

or use

mkdir nonexistent

first.


To automatically generate all the directories for a filepath:

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

Tags:

Bash

Redirect