Search code examples
bashpermissionscron

Bash - Permission denied error when logging to /var/log/<file-name>


For an application I want to store specific data on a data recovery server. On the application and DR server I created a user test1 and copied the public key from application server user test1 to DR user test1's authorized_keys file. User test1 is added to the wheel group.

I set permission on drwxr-xr-x /var/log

I then created a cron job to rsync the data from the application server to the DR server:

sudo rsync -avz -e "ssh -i /home/test1/.ssh/my-ssh-key" /var/nfsshare/ test1@10.10.10.10:/var/nfsshare > /var/log/nfs_cron-$(date +\%m-\%d-\%Y).log

When the cron executes I get the following error:

/bin/sh: /var/log/nfs_cron-08-26-2019.log: Permission denied

However, when I try to create a file manually it creates the file successfully.

sudo touch /var/log/test.txt

which creates the file as:

-rwxr-xr-x.  1 test1 test1 0 Aug 26 12:28 test.txt

Any thoughts?

Thanks!


Solution

  • You can create a directory and give permission to this user or you can use redirection/tee to write the log file.

    For example using ACL: mkdir -p /var/log/my_app/ setfacl -Rm g:MY_GROUP_ID:rwx /var/log/my_app/

    The setfacl command is to setup ACL.

    -R -> It's to be recursive and setup the ACL to all subfolder

    -m -> It's to modify the ACL

    goru -> It's to define the group or user

    rwx -> It's the permission to setup for the group/user

    http://tldp.org/LDP/abs/html/abs-guide.html#SETFACLREF


    Another way is using redirection/tee. With redirection, you can "filter" what you want log into the file. For example:

    Log and/or concatenate just in case of success

    ls -lZ /tmp/myfile >> /var/log/mylog
    

    Log everything (Sending stderr to stdout and writing into the same file)

    ls -lZ /tmp/myfile >> /var/log/mylog 2>&1
    

    or just use &>

    ls -lZ /tmp/myfile &> /var/log/mylog
    

    If you don't have permission to write on the destination file/directory, you can use tee to write. For example, appending (-a) and writing into the file /var/log/mylog.

    ls -lZ /tmp/myfile | sudo tee -a /var/log/mylog
    

    You can find some other examples and a better explanation in here:

    https://www.tldp.org/LDP/abs/html/io-redirection.html

    https://wiki.bash-hackers.org/howto/redirection_tutorial

    https://wiki.bash-hackers.org/syntax/redirection