0

I need to write a shell script .sh file which is creating a zip file from /var/www as a sudo user.


I have my Ubuntu server and my site hosted on it which means my source code is in /var/www folder. But /var/www has writeable permissions only for root user.

I want to write a script for backing up the /var/www folder as a zip every time I run that script with no need to ask root user password.

  • Hi & Welcome to AU. What are you referring to as "a sudo user"? Executing part or including in shell script. :) – AzkerM Jul 16 '14 at 6:02
  • So you want the script to run as root? Are you looking for if [ "$UID" != "0" ]; then echo not root; fi? – Elliott Frisch Jul 16 '14 at 6:08
  • I need shell script code, /var/www folder having only accessed by root user. – Upendra Jul 16 '14 at 6:08
  • What does "/var/www folder having only accessed by root user" mean? – Elliott Frisch Jul 16 '14 at 6:10
  • I will explain my complete requirement :: I have my ubuntu server, and my site hosted on it, means my source code in /var/www folder. here /var/www folder writable permissions only for root user. I want to write a script for backingup that (/var/www)folder as a zip when I run that script. (no need to ask root user password) – Upendra Jul 16 '14 at 6:13
3

Hi & Welcome to AskUbuntu,

Well, I'm not sure why /var/www directory is been owned by root while technically it should be www-data who'll be the owner & the group as default. Nevertheless, the simplest way to achieve this is using below script which I use to compress some of my directories. I'm using tar command instead.

Creating a shell script

  • open a terminal (with CTRL+ALT+T) & create a new bash file.

  • type the command nano filenam.sh & paste below (alter the script according to your need).

#!/bin/bash 

TIME=`date +%F-%H%M%S`                   # time stamp to the backup file
FILENAME="backuup nam-$TIME.tar.gz"      # defining the format of the file name while backing up
SRCDIR="/home/parth/to/source"           # Location of the backup directory
DESDIR="/home/path/to/destination"       # Destination of the backup directory (where you need to backup)
tar -cpzf $DESDIR/$FILENAME $SRCDIR      # Executing the command
  • save the script (with CTRL+O & enter). Then exit (with CTRL+X).

Executing the command

  • Simply run sudo sh filename.sh to perform (sudo will run with root previledge)

You may also add this to a cronjob which will automate the process according to your needs. This bash script append a time stamp and backup on an incrimental basis. Its just a simple script that I took and altered to your ease.

Refer official Ubuntu Documentation on Shell Scripts & bash script which I took from BroExperts.

Hope it helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.