By default files created with root accound have permissions like so:
-rw-r--r-- 1 root root 0 11月 17 23:25 rootfile.txt
Here file belongs to root user and root group, and is readable and writable by root, but only readable by others.
Simplest approach would be just to chown
the file back to the original user.
chown username:group_name dummy.txt
You can use $SUDO_USER
variable that is accessible only when sudo
is called, like so:
chown "$SUDO_USER":"$SUDO_USER" dummy.txt
If you're running script as regular user, the chown
part is not needed at all, so you might want to consider using if-statement or &&
test to test for the case when script is run as root, and do something along these lines:
#!/bin/bash
touch dummy.txt
[ $UID -eq 0 ] && chown "$SUDO_USER":"$SUDO_USER" dummy.txt
The above is recommended approach. There are others, like using chmod
to change read-write-execute permissions for users and group, but it's not recommended.
chown
andchmod
in your script to set ownership and permissions as desired. – fkraiem Nov 18 '16 at 09:33