Ignore sudo in bash script

You could test if the script is being run via sudo using the EUID and SUDO_USER variables, and then execute touch as SUDO_USER if true - something like

#!/bin/bash

if [[ $EUID -eq 0 ]] && [[ -n $SUDO_USER ]]; then
  sudo -u "$SUDO_USER" touch dummy.txt
else
  touch dummy.txt
fi

If your script is not meant to be run as root, the safest way to solve the problem is to abort the execution of the script at the very beginning:

if [ "$EUID" = 0 ]; then
   echo "This script must NOT be run as root" 
   exit 1
fi

Optionally, you can re-execute your script as a fallback user (e.g. sudo -u FALLBACK_USER "$0") instead of simply aborting.

Trying to fix the quirks of individual commands will make your script unnecessarily complex and hard to debug. Every time you modify it, you'll have to do all the testing twice (as a regular user, then as root), and fix all the root-related bugs that arise. It's not a future-proof solution, so to say.


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.