[Gllug] spaces and shell scripting

Alain Williams addw at phcomp.co.uk
Thu Sep 1 13:59:04 UTC 2005


On Thu, Sep 01, 2005 at 02:43:50PM +0100, Jon Dye wrote:
> Hi,
> 
> I'm trying to write a shell (bash) script that uses find to get a list 
> of file names and do different things depending on whether there are 0, 
> 1 or more items in the list.
> 
> My problem is spaces in filenames and how to deal with them when I have 
> a list of file names in a variable.  I got the script to work by running 
> find multiple times and not using variables, e.g.
> 
> FILE_COUNT="find /some/directory -print | wc | cut -c 1"

Do it once rather than several times:

	FILE_COUNT=$( find /some/directory -print | wc -l )

> if [ $FILE_COUNT -eq 0 ]; then
> 	# do something
> elif [ $FILE_COUNT -eq 1 ]; then
> 	# do something else
> 	FILE=`find /some/directory -print`
> 	some_command "$FILE"
> else
> 	# do something with the list of files
> 	find /some/directory -print0 | xargs -o some_other_command

If you give find '-print0' you must give xargs '--null', or is '-o' supposed
to be '-0' ?

> fi
> 
> but I want to avoid multiple find statements because they are slow.  I 
> guess I want either to put the list of files in a variable with 
> delimiters between the file names or put them into an array somehow.
> 
> If any can tell me how to achieve what I want (or suggest a better way 
> to do it) I'd be grateful.

I don't see why you just don't do it using find/xargs:

	find /some/directory -print0 | xargs --null --no-run-if-empty some_other_command

--no-run-if-empty stops it doing anything if there is nothing to do.

> Thanks,
> 
> JD
> -- 
> Gllug mailing list  -  Gllug at gllug.org.uk
> http://lists.gllug.org.uk/mailman/listinfo/gllug

-- 
Alain Williams
Parliament Hill Computers Ltd.
Linux Consultant - Mail systems, Web sites, Networking, Programmer, IT Lecturer.
+44 (0) 787 668 0256  http://www.phcomp.co.uk/

#include <std_disclaimer.h>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mailman.lug.org.uk/pipermail/gllug/attachments/20050901/0068d397/attachment.pgp>
-------------- next part --------------
-- 
Gllug mailing list  -  Gllug at gllug.org.uk
http://lists.gllug.org.uk/mailman/listinfo/gllug


More information about the GLLUG mailing list