[Gllug] Shell scripts

tet at accucard.com tet at accucard.com
Fri May 3 09:49:00 UTC 2002


> I have a script that removes a load of files from a directory tree
> and then copies a load of files in to replace the removed ones (from
> several sources).

A better option is to copy the new file in and then rename it to be
the old one:

	cp "/somewhere/else/$newfile" "$oldfile.$$"
	[ $? -eq 0 ] && mv "oldfile.$$" "$oldfile"

mv is an atomic operation in the filesystem (for the common cases, anyway),
while cp isn't. Doing the above ensures that if the cp fails half way
through, you don't end up with corrupt files.

>What I want to do is provide some sort of progress information
>and I thought I could do this by getting a list of the files that are going
>to be deleted and then deleting them one at a time and calculating the
>percentage of files deleted.
>This seems like a horrible idea as it would be spawning lots of processes so
>does anyone have any other suggestions?

You don't need to spawn any processes these days, you can do it all with
shell arithmetic. But even in the past, you'd only need to have spawned
a single process (either a dc or a bc) per iteration.

>Also, I'm using find to list the files but I can't get the splitting to work
>correctly:
>
>FILES=$(find <mypath> <criteria>)
>echo ${FILES[0]}
>echo ${FILES[1]}
>echo ${#FILES[@]}
>
>shows a list of all files in ${FILES[0]} and none in ${FILES[1]}, while
>${FILES[@]} is 1

I'd do something like:

	files=$(find /mypath <criteria> -print)

	numfiles=$(echo $files | wc -w)
	count=0
	for file in $files
	do
		### Do some stuff here (copy/remove files, etc.)

		count=$((count + 100))
		percentage=$(($count / $numfiles))
		echo "${percentage}% complete: $file"
	done

Note that this method of iterating throught the files doesn't handle
filenames containing whitespace, but is otherwise fairly reasonable.
Also note the use of lower case variable names. By convention, upper
case is reserved for environment variables. Shell variables should be
lower case.

Tet

-- 
Gllug mailing list  -  Gllug at linux.co.uk
http://list.ftech.net/mailman/listinfo/gllug




More information about the GLLUG mailing list