How to set specific file permissions when redirecting output?

I know it's an old question, but I wanted to add my two cents.

I had the same idea and came up with a solution similar to BowlesCR. The problem with his solution was that my command (foo) wouldn't work if I changed the umask before running it, so this is my take on the problem:

foo | ( umask 0033; cat >> /tmp/foo.log; )

Here, umask only affects the redirection to foo.log in the subshell. Everything else remains unaffected.

A bit convoluted, but it works.


Without true scripting, you can chain a bit:

touch /tmp/foo.log; chmod 0644 /tmp/foo.log; foo >> /tmp/foo.log

Effectively similar to Slowki's answer, but condensed into a one-liner.

The only other thing I can think of is tinkering with the umask. Best to do this in a subshell so it doesn't pollute the current environment:

(umask 0033 && foo >> /tmp/foo.log)

Two issues with that, though.

  1. Umask can't raise the permissions above the level specified in the creat() syscall (0666 appears to be what Bash uses).
  2. This won't change the permissions on an existing file (because umask applies only to file creation).

There's no way to do it while piping as far as I know, a simple script might be the best solution.

if [ -e /tmp/foo.log ]; then
    foo >> /tmp/foo.log
else
    foo >> /tmp/foo.log
    chmod 0644 /tmp/foo.log
fi