I have written a function which acts in a similar way to tee
but also pre-pends a datestamp. everything works fine except when i want to output to a file which is only root writable (in my case a logfile within /var/log
). I've simplified the following code snippet to just include the bits which are not working:
#!/bin/bash
#script ~/test_logger.sh
logfile=/var/log/test.log
logger()
{
while read data
do
echo $data >> $logfile
done
return 0
}
sudo ls ~ | logger
it works fine if i run the whole script like so sudo ~/test_logger.sh
but i can't always do this since i want to use the logger function in files like ~/.bash_logout
which are run automatically. i've tried putting sudo
in front of the echo in the while loop but this does not work. any ideas?
Best Answer
it's generally bad practice to put
sudo
in a script. A better choice would be to call the script withsudo
from~/.bash_logout
or wherever else you want to use it, if you must, or better still just make/var/log/test.log
world-writable.