Using chown $USER:$USER inside bash script
If, for some reason, $USER
is not set, you can use the id
command to obtain the identity of the real user. So the first time you use the $USER
variable, you can use the shell expansion to supply a default value. Change the chown
line in your script to:
sudo chown ${USER:=$(/usr/bin/id -run)}:$USER /var/www/$sitename
If USER
is empty or unset when this is run, bash will set the USER
variable to the output of /usr/bin/id -run
When I calling my script with sudo
it would set $USER
to root.
$ sudo ./myscript.sh
I tried the chown ${USER:=$(/usr/bin/id -run)}:$USER /var/www/$sitename
but it would still return root.
I found if I used who
with awk
I was able to get the current user that called the script with sudo
.
currentuser=$(who | awk '{print $1}')}
chown -R $currentuser:$currentuser /var/www/$sitename`
In order to simplify the problem and since your are getting the variable sitename, why don't you read a username variable?
With that you'd make sure that the script execution is not dependent on the environmental variables made available the way the script is executed.