Bash Scripting

Top Page
Attachments:
Message as email
+ (text/plain)
Delete this message
Reply to this message
Author: der.hans
Date:  
Subject: Bash Scripting
Am 13. Apr, 2002 schwätzte Bryce C. so:

> Could anyone give me some help with some bash scripting. I'm trying to
> write a script for an hourly back up but I don't know how to add a
> timestamp in to the tar output file name. What I have currently (with
> confidential parts hidden) is:
>
> #!/bin/bash
> su _USER_ -c "cd /home/_USER_; tar -czf
> _NFSMOUNT_/_FILENAME_._COMPUTERNAME_._DATE_.tar.gz _DIRECTORYTOBU_/"
>
> Anything with _TEXT_ is the ommitted text except for the _DATE_. Anyone
> please?


I toss the date in the format I want into a variable, then use that
variable. That variable should be expanded just fine. The key is to make
sure that it gets assigned and that it doesn't have any spaces in it.

In my script below you could add the following two lines after the $DATE
variable is assigned to make sure you're getting what you want.

echo "<$DATE>"
exit

The angle-brackes act as delimiters in the output to show you exactly what
the $DATE variable contains.

If you su with a dash, then you should go to their home dir, so you don't
need the cd. If you don't trust that you should get the home path from
/etc/passwd.

It looks like you're only backing up one dir within the home dir. If you
want to backup the entire home dir, then you should do that from one dir up
to get all the dotfiles. That will add an extra-level to the path that's
backed up.

You don't need to su unless you're wanting the user to be able to access the
backup directly. That's a good idea, but you should remove their write perms
afterwards.

You might want to add the -l option to make sure you don't wander down any
SMB mounts.

You can also use the -C option to do the cd.

#!/bin/bash

USER=$1
if [ $2 ] ; then
    if [ $2 = 'full' ] ; then
        FULL=yes
    fi
fi


DIR2BACKUP=something
NFSMOUNT=something
FILENAME=something
HOSTNAME=`hostname`

DATE=`date +%d%b%Y`
USERSHOME=`grep ^$USER: /etc/passwd | cut -f 6 -d :`
TARBALL=$NFSMOUNT/$FILENAME.$HOSTNAME.$DATE.tar.gz

if [ $FULL = 'yes' ] ; then
    DIR2BACKUP=`basename $USERSHOME`
    su $USER -c "tar clzf $TARBALL -C $USERSHOME/.. $DIR2BACKUP/"
else
    su $USER -c "tar clzf $TARBALL -C $USERSHOME $DIR2BACKUP/"
fi


chmod w-a $TARBALL

# end

Check for typos and bad code. Munge for your purposes. Translate to Swahili.

ciao,

der.hans
--
# https://www.LuftHans.com/
# Two roads diverged in a wood, and I --
# I took the one less traveled by,
# And that has made all the difference. -- Robert Frost
# I, OTOH, prefer to just go stomping through the desert... - der.hans