bash shell-script terminal gnome-terminal chown – Using chown $USER:$USER in Bash Script

bashchowngnome-terminalshell-scriptterminal

In a small bash script I'm running I am attempting to chown a new directory that is created. I've added:

sudo chown $USER:$USER /var/www/$sitename
sudo chmod 775 /var/www/$sitename

after the line where I mkdir (sudo mkdir /var/www/$sitename).

For some reason the chown is not executing. I can execute it manually but when written in the file it doesn't work. I have noticed that "chown" is not highlighted in the same color as "mkdir" and "chmod" but I can't figure out my problem.

Why doesn't chown work here?

Is it an issue with $USER:$USER?

EDIT
Here is the full script. How would I chown the file to whichever non root user executed the script?

#!/bin/sh
#!/bin/bash
# New Site

cd /etc/apache2/sites-available/
echo "New site name (test.my):"
read sitename
echo "<VirtualHost *:80>

        ServerAdmin admin@$sitename

    ServerName $sitename

        ServerAlias $sitename

    DocumentRoot /var/www/$sitename

        <Directory />
                Options FollowSymLinks
                AllowOverride All
        </Directory>
        <Directory /var/www/$sitename>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride All
                Order allow,deny
                allow from all
        </Directory>

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined


</VirtualHost>" > $sitename.conf
sudo mkdir /var/www/$sitename
sudo chown $USER:$USER /var/www/$sitename
echo USER is $USER
sudo chmod 775 /var/www/$sitename
sudo a2ensite $sitename.conf
sudo apachectl restart
echo "New site created"

Best Answer

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

Related Question