views:

212

answers:

3

What is a generalized way to create a bash script from another script.

For instance:

$./script1 arg1 arg2 > script2
$./script2
$arg1 arg2

I can think of a few ways like simply echoing the output but I was wondering if there was a better way or a command I didn't know about and a google search wasn't very helpful.

Thanks in advance for any and all help.

+2  A: 

Any way of outputting from the first script will work, so echo or cat with a heredoc should be fine:

cat << EOT
these will be
the lines of
the second script
EOT
calmh
But I couldn't include variables from the first script could I?
Ranman
You can include anything it's possible to write to a file, the same as if you were writing the second script with a text editor.
Wooble
@Ranman: Variables are substituted in here documents, so you can assign something to shell variable foo, then use $foo in the sectionyou want to output, and it'll do what you want.
Jim Lewis
@Ranman: you can. Look for "here documents" in `man bash`: "If word [EOT] is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion."
outis
+1  A: 

If you don't need the extra file

$ script1 arg1 arg2 | bash

or, if you want a file

$ script1 arg1 arg2 | tee script2 | bash
nicerobot
It is often easier to debug the script if you capture it in a file, though. Also, sometimes you don't want the script executed unconditionally - you want the user to check it over beforehand. But you can do as you say (and I've occasionally done it), hence my +1.
Jonathan Leffler
Oh, one other advantage of a separate script file; none of the script gets executed until the file is complete, whereas a piped script could be partially executed before the generation is complete If an error occurs, you might want not to execute anything, but the pipe scenario leaves you without that option (you can't rely on the shell executing nothing, in general). Demo: `cp /dev/null junkfile; { echo "rm junkfile"; sleep 300; } | bash`; suspend the shell and you'll find that junkfile is MIA.
Jonathan Leffler
+1  A: 

Generally, when you have one file create another, you are performing some kind of templating. While bash is capable of this, you may want to consider another tool. m4 is a popular tool used in the GNU tool chain. For even more basic templating, you can do something like the following perl script:

perl -pne BEGIN { open my $fh, $ENV{SERVER_PROPERTIES_FILE} or die $!; \
%hash = map { chomp; split /=/ } <$fh>; } s/\${(.*)}/$hash{$1} or die "missing $1"/eg' <     "${SERVER_XML_FILE}

If you don't need a second file, you can accomplish most things within a bash script using here documents and inline execution.

brianegge