[Gllug] Variable substitutuion in bash

Russell Howe rhowe at wiss.co.uk
Sat Sep 11 19:10:15 UTC 2004


On Sat, Sep 11, 2004 at 07:42:04PM +0100, Dylan wrote:
>  I have a variable $comments which contains a list of comment options 
> for oggenc, e.g.:
> 
> music at audio:/media/music/test> echo $comments
> -c "ALBUM=Milestones" -c "ARTIST=10cc" -c "DESCRIPTION=" -c "GENRE=" -c 
> "KDE-ENCODER=kio_audiocd" -c "TITLE=Im Not In Love" -c "TRACKNUMBER=7"

Why not use bash's array variables for this?

comments=("-c" "ALBUM=Milestones" "-c" "ARTIST=10cc" -c "DESCRIPTION="
-c "GENRE=") # etc...

That way you can use all the fancy stuff like ${#comments[@]} to get the
number of commandline options (divide by two to get the number of
attributes), "${comments[@]}" to get a quoted list of all parameters,
"${comments[*]}" to get an unquoted list of all parameters, and the
ability to add a new parameter simply by doing this:

#!/bin/bash

# attributes would've been filled in previously, somehow
attributes=('ARTIST=foo' 'GENRE`echo hi`=$crap') # Our OGG file
                   # contained evil stuff, trying to exploit the system!

cmdlineopts=()
optioncount=0

for attribute in "${attributes[@]}"; do
        cmdlineopts[$((optioncount++))]="-c"
        cmdlineopts[$((optioncount++))]="$attribute"
done

echo "Commandline options are: ${cmdlineopts[*]}" # Remember to use
                                     # "${cmdlineopts[@]}" to quote it!

# oggenc "${cmdlineopts[@]}"

Note that this doesn't execute any child processes (assuming echo is a
bash builtin), and so is fast. The minute you execute sed, awk, grep,
etc, you cause bash to fork() which can place a heavy load on the system
if you're processing large numbers of files and fork()ing $n times for
each one!

-- 
Russell Howe       | Why be just another cog in the machine,
rhowe at siksai.co.uk | when you can be the spanner in the works?
-- 
Gllug mailing list  -  Gllug at gllug.org.uk
http://lists.gllug.org.uk/mailman/listinfo/gllug




More information about the GLLUG mailing list