Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: (feature request) Shell script within shell script



On Feb 1,  2:36am, William Park wrote:
} Subject: Re: (feature request) Shell script within shell script
}
} Essentially, I wish I could do something like
}     
}     herefile test1 << "EOF"
}     #! /usr/bin/gawk -f
}     ...
}     ...
}     EOF

Effectively, what you want to do is create a temp file and then execute
it.

That's as simple as:

    herefile () {
      setopt localtraps noshwordsplit
      local tmp=${TMPPREFIX}HERE$$
      trap "command rm -f $tmp" EXIT
      : >| $tmp				|| return
      chmod u=rwx,go-rwx $tmp		|| return
      cat >| $tmp			|| return
      $tmp $@
    }

Try it with this silly example:

    herefile <<\EOF
    #! /bin/ls -l
    EOF

The tricky bit of course is that the redirection becomes the standard
input of the "herefile" function, so your script will see end-of-file
as soon as it starts running.

You can avoid this by doing some file descriptor manipulations:

    _herefile () {
      setopt localtraps noshwordsplit
      local tmp=${TMPPREFIX}HERE$$
      trap "command rm -f $tmp" EXIT
      : >| $tmp				|| return
      chmod u=rwx,go-rwx $tmp		|| return
      cat >| $tmp			|| return
      $tmp $@ <&3 3<&-
    }
    alias herefile='_herefile 3<&0'

    herefile /etc/HOSTNAME /etc/issue <<\EOF
    #! /usr/bin/perl -p
    BEGIN { print join("\n\t", 'Printing these files: ', @ARGV)."\n\n"; }
    EOF

This of course has the drawback of always consuming file descriptor 3,
so it may not work well with other scripts or functions that do lots
of file-descriptor swapping.  You can pick another descriptor number 
if you think it'll make collisions less likely.

-- 
Bart Schaefer                                 Brass Lantern Enterprises
http://www.well.com/user/barts              http://www.brasslantern.com

Zsh: http://www.zsh.org | PHPerl Project: http://phperl.sourceforge.net   



Messages sorted by: Reverse Date, Date, Thread, Author