is there a /bin/sh method to tell the ending of a file

Christopher Cowart ccowart at rescomp.berkeley.edu
Tue Jan 8 10:13:49 PST 2008


On Tue, Jan 08, 2008 at 12:01:18AM -0600, Jon Hamilton wrote:
> } On Mon, Jan 07, 2008 at 09:10:58PM -0800, Gary Kline wrote:
> } Paul Procacci <pprocacci at datapipe.com>, said on Mon Jan 07, 2008 [11:34:08 PM]:
> } > Hi All,
> } > 
> } > Is there an easy way of determing whether a string//filename ends in
> } > *.gz? using /bin/sh?  
> 
> } Is this what you mean?
> } 
> } ---------------------
> } #!/bin/sh
> } 
> } STRING="mystring.gz"
> } 
> } if [ ".gz" = "`echo \"$STRING\" | sed -n 's/.*\(\.gz\)$/\1/p'`" ]; then
> }  echo test;
> } fi
> } 
> } -----------------------
> 
> Works (I assume) but perhaps easier to read and more "native" might be:
> 
> case "$STRING" in
> *\.gz)
>   echo "Found .gz suffix"
>   ;;
> *)
>   echo "Not a .gz suffix"
>   ;;
> esac
> 
> Sh is a pretty versatile creature; I'm sure there are a thousand more ways
> all of which work, and some of which will cause religious arguments for 
> decades :)

Right. Here's another way using parameter expansion:

| if [ ${STRING##*.} = gz ] ; then
|     echo true
| else
|     echo false
| fi

The syntax is terse, but pretty popular in the /etc/rc family of scripts. 

-- 
Chris Cowart
Lead Systems Administrator
Network & Infrastructure Services, RSSP-IT
UC Berkeley
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 825 bytes
Desc: not available
Url : http://lists.freebsd.org/pipermail/freebsd-questions/attachments/20080108/6ce84bc8/attachment.pgp


More information about the freebsd-questions mailing list