[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: shell script and variable problem

On Fri, Dec 01, 2006 at 03:42:18PM -0800, John L Fjellstad wrote:
> I have the following script I use for backup:
> #######
> #!/bin/sh
> BACKUPLIST=/etc/backup.lst
> HOSTNAME=`hostname`
> YEAR=`date +%Y`
> MONTH=`date +%B`
> BACKUPDIR=/srv/misc/backup/${YEAR}/${MONTH}
> DATE=`date +%Y%m%d`
> mkdir -m 2775 -p $BACKUPDIR
> for entry in `cat $BACKUPLIST`; do
>         name=`echo $entry | cut -d':' -f1`
>         startdir=`echo $entry | cut -d':' -f2`
>         bkdir=`echo $entry | cut -d':' -f3`
>         exlist=`echo $entry | cut -d':' -f4`
>         if [ -n $exlist -a -f $exlist ]; then
>                 cd $startdir; tar -X $exlist -cf - $bkdir | bzip2 -c > ${BACKUPDIR}/${HOSTNAME}-${name}-${DATE}.tar.bz2
>         else
>                 cd $startdir; tar cf - $bkdir | bzip2 -c > ${BACKUPDIR}/${HOSTNAME}-${name}-${DATE}.tar.bz2
>         fi
> done
> ##########
> Now, /etc/backup.lst has a list of directories I want to backup, and
> looks like this
> john:/home:john:/home/john/backupex.lst
> vcs:/srv:/srv/vcs:
> That is, some entries have 4th field, some has not.
> The problem is that my test
> if [ -n $exlist -a -f $exlist ]
> does not work.  For some reason, this always evaluate to true, and then
> the tar command fails.  Why is this?

Not sure, but it'll work if you enclose the variable in quotes.

> My understanding is -n will check if $exlist is empty or not, and if it
> is, it will fail.  And even if it doesn't, -f $exlist should fail since
> it wouldn't be able to find that file.

My guess is that the variable expands to nothing, and then the -n
test is applied to the next token it sees, perhaps the -a?

I've run into the same issue recently, and would like to somehow become
less baffled by the ins and outs of shell (bash) scripting.  Presumably
there's a statement in bash(1) that would clarify what's going on.


Ken Irving, fnkci@uaf.edu

Reply to: