The answer you need is to run your command as follows (or in a similar way):
sudo -u w3svcsadm bash -c 'echo "TEST ran" > /home/youribm/emaildigest/TEST_$( date +%Y%m%d%H%M%S ).output'
The difference is:
in your version, the sudo means that echo "TEST ran"
is being run as w3svcsadm
. The > /home/youribm/emaildigest/TEST_$( date +%Y%m%d%H%M%S ).output
is being run as your current user, which is apparently root.
what you actually want is for the whole block, including redirection, to be run as w3svcsadm
. In my suggestion, I achieve that by running bash
as w3svcsadm
, and telling bash
to run the full command-line (echo "TEST ran" > /home/youribm/emaildigest/TEST_$( date +%Y%m%d%H%M%S ).output
), and then exit.
Or, in simpler terms: redirection is a form of piping between two commands, and in your case, you want both commands to be run by the same user.
It may help to mentally replace >
with ;
(or &&
) to understand: command one is echo
, and command two is write standard input into this file
.
The first 'half' of the command (before redirection) is being run by sudo, and the rest is not.
Although we generally consider a command with output redirection as one command, it isn't - it is two commands, and so you need to ensure both commands are being run by the user you intended.