Linux – How to set specific file permissions when redirecting output

bashcommand linefile-permissionslinuxshell

This is probably a duplicate, but all my searches are turning up questions about permission denied errors.

I am running a command in a bash shell. I want to redirect output to append to a file that probably does not exist on the first run. I want to set specific file permissions mode if output redirection has to create this file. Is there a way to do this with one command?

For example, I might try

foo >> /tmp/foo.log 0644

where 0644 are the permissions I want foo.log to end up with. Most commands I've experimented with in bash end up interpreting 0644 as an additional argument to foo.

I get the feeling that this is going to take a second command to chmod the permissions before or after writing to it.

I am using GNU bash 4.2.25 and Ubuntu 12.04, if that makes a difference – general answers are preferred.

Best Answer

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
Related Question