[Gllug] Bash: Escaping a *

C. Cooke ccooke at gkhs.net
Sun Jun 27 09:36:52 UTC 2004


On Sun, Jun 27, 2004 at 12:53:04AM +0100, Russell Howe wrote:
> On Sat, Jun 26, 2004 at 09:13:08PM +0100, Darren Beale wrote:
> > Dean Wilson wrote:
> > 
> > >Try echo "$SQL" instead.
> > 
> > Perfect, thanks
> > 
> > ;D
> 
> Unquoted shell variables are an accident waiting to happen.
> 
> Imagine if $SQL somehow managed to contain "`rm -rf ~`".
> 
> I'll leave it as an exercise to the reader to see what that does...
> 
> Always quote your shell variables (the only exception being when you
> want to do something like:
> 
> OPTS=-a -b -c
> 
> /usr/bin/program $OPTS "$foo"
> 
> Anyone know a fancy way to do that safely? I know there's the special
> "$@" which expands to "$1" "$2" "$3" ... "$n" for parameters, but I
> don't think there's a generalised version, or is there?
> 

Sure. Assuming bash:

# Create an array, "OPTS"
OPTS=( "-a" "-b" "-c" )

/usr/bin/program "${OPTS[@]}" "$foo"

Other times when it's safe:

You can easily discard the stuff that's not safe:

# Strip out stuff you don't want
String="${String//[![:alnum:]other-stuff-you-want]/}"
# After this, $String is safe


using ksh93, you can define types on things. For instance:

# Safely handle $1, throwing errors if it's not an int
integer Value="$1"

# From here, $Value is safe.



-- 
Charles Cooke, Sysadmin
Say it with flowers, send a triffid.
-- 
Gllug mailing list  -  Gllug at gllug.org.uk
http://lists.gllug.org.uk/mailman/listinfo/gllug




More information about the GLLUG mailing list