Bash: redirect to file, always create new

bashio-redirectionsymlink

In bash, a command link

echo test > actual.txt

will replace the contents of the file called actual.txt with "test", and create the file if it doesn't exist. However, if the file does exist, bash will just open it, truncate it, and write the new contents into the file.

Specifically, the redirect command fails in this scenario:

ln -s /some/illegal/path link.txt
echo test > link.txt

Bash 4.4.12 gives me the confusing error message link.txt: No such file or directory.

One way to avoid this is to make sure to delete the file before running the redirected command.

rm link.txt && echo test > link.txt

I was wondering, though, if there was some tweak of bash options or the redirect operator which will prevent this failure mode. Any ideas?

Best Answer

Trying to write to a dead symbolic link is equivalent to trying to write to a path that does not exist. There is no way to "tweak" the output redirection to create the path (including intermediate directories) in bash, and there are no shell options in bash that makes this automatic.

If the intermediate path exists, but the end point of the link does not, then it will be created by the redirection.

You may do something like

if [ -h file ] && [ ! -f file ]; then
    rm file
fi

to test whether "file" is a symbolic link (-h) and whether it refers to a regular file that exists (-f). If it is a symbolic link but does not refer to a file, then you delete it.

Related Question