[Home]PeterTaylor/Preprocessor

ec2-3-215-16-238.compute-1.amazonaws.com | ToothyWiki | PeterTaylor | RecentChanges | Login | Webcomic

I needed a preprocessor for some stuff I'm working on. I tried m4, but I was pulling my hair out trying to get it to process files containing apostrophes. So I wrote one.
#!/bin/sh

DEBUG=false
PREPROCESSOR_OUT=`tempfile`

function include()
{
    cat ${1:?File not specified} |
        while read PREPROCESSOR_CMD PREPROCESSOR_LINE
        do
            case $PREPROCESSOR_CMD in
                "#INCLUDE")
                    include $PREPROCESSOR_LINE
                    ;;

                "#DEFINE")
                    echo "export $PREPROCESSOR_LINE" >>$PREPROCESSOR_OUT
                    ;;

                "#IFDEF")
                    echo "if [ ! -z \$$PREPROCESSOR_LINE ] ; then" >>$PREPROCESSOR_OUT
                    ;;

                "#IFNDEF")
                    echo "if [ -z \$$PREPROCESSOR_LINE ] ; then" >>$PREPROCESSOR_OUT
                    ;;

                "#ELSE")
                    echo "else" >>$PREPROCESSOR_OUT
                    ;;

                "#ENDIF")
                    echo "fi" >>$PREPROCESSOR_OUT
                    ;;

                *)
                    echo "$PREPROCESSOR_CMD $PREPROCESSOR_LINE" |
                        sed -e 's/"/\\"/g' -e 's/\(.*\)/echo "\1"/' >>$PREPROCESSOR_OUT
                    ;;
            esac
        done
}

if [ -z $1 ]
then
    PREPROCESSOR_IN=`tempfile`
    cat >$PREPROCESSOR_IN
    include $PREPROCESSOR_IN
    rm $PREPROCESSOR_IN
else
    include $1
fi

if $DEBUG
then
    cat $PREPROCESSOR_OUT
else
    . $PREPROCESSOR_OUT
fi

rm $PREPROCESSOR_OUT


Bugs


The final line must be terminated with a newline character, because read expects this. I can't see a workaround for this. Does anyone know of a replacement for read I could use?
Create your own by wrapping read -n 1 in a while loop that bails on newline? - MoonShadow
Maybe. But in starting to work towards that, I discovered that things are far murkier than I thought.
pjt33@charis:/tmp/$ unset FOO
pjt33@charis:/tmp/$ cat read.sh
#!/bin/bash
read FOO
echo $?
echo $FOO
pjt33@charis:/tmp/$ cat test
This file has one line.pjt33@charis:/tmp/$ # This is a comment at a prompt, not part of ./test.
pjt33@charis:/tmp/$ cat test | read FOO
pjt33@charis:/tmp/$ echo $?
1
pjt33@charis:/tmp/$ echo $FOO

pjt33@charis:/tmp/$ cat test | ./read.sh
1
This file has one line.
pjt33@charis:/tmp/$ 


ec2-3-215-16-238.compute-1.amazonaws.com | ToothyWiki | PeterTaylor | RecentChanges | Login | Webcomic
Edit this page | View other revisions | Recently used referrers
Last edited October 3, 2005 8:07 pm (viewing revision 6, which is the newest) (diff)
Search: