Shell script that generates another shell script

If there's a file called example.txt with contents:
Foo
Bar
Baz
Goo

then I need to generate a shell script that has commands to reconstruct example.txt on another machine:

echo "Foo" >> example.txt
          echo "Bar" >> example.txt
          echo "Baz" >> example.txt
          echo "Goo" >> example.txt

I use for i in * to search a directory and conduct the above operation on every file that's not binary. Suppose i points to example.txt now, as the above example shows. I used sed to extract the contents of the files line by line. The question is how to use the result extracted by sed as the argument of echo?

I tried:

number=`wc -l < $i`
          count=1
          while [ $count -le $number ]
          do
          tmp=`sed -n "$count,1p" $i`
          echo ' echo "$tmp" >> $i ' >> bundle.sh
          done 

Here tmp is the content of each line, but $tmp didn't evaluate in echo.

Actually the purpose of doing so is to transfer a directory containing various files and subdirectories which also contain files to another machine through simple email. Only bundle.sh needs to be transferred. So when the shell script bundle.sh is run on the other machine, the whole directory will be constructed there. I'm writing a script that can generate the bundle.sh script. And of course this needs to be done recursively since there're subdirectories, but ignore it for now. Thanks.

Here is a url to the full description of the task:

Instead of generating a file that regenerate the file, why don't you just generate a copy of the file ?

If you want to copy a directory with subtree, see
tar command as well as cp or scp command (see -R and -r options)

1 Like

How about this ?

$ cat test123
foo
bar
baz
goo
foo baar
$ cat p33.sh
#!/bin/sh

i=test123
number=`wc -l < $i`
count=1
while [ $count -le $number ]
do
     tmp=`sed -n "$count,1p" $i`
     echo "echo $tmp >> $i" >> bundle.sh
     count=$(($count + 1))
done
$ cat bundle.sh
echo foo >> test123
echo bar >> test123
echo baz >> test123
echo goo >> test123
echo foo baar >> test123
1 Like

actually it's a homework, so I'm supposed to do it using my own code. Thanks.

---------- Post updated at 10:00 AM ---------- Previous update was at 10:00 AM ----------

thanks a lot.

---------- Post updated at 02:35 PM ---------- Previous update was at 10:00 AM ----------

hi, could you pls explain why there shouldn't be a double quote in $tmp and why count=$(($count + 1)) should be used to increase count? many thanks.

I'd rather use either: ((count++)) OR let count++
hth

EDIT:
The double brackets sends count++ to subshell, while let does it arithmeticly (AFAIK)

Homework items can only be posted in the Homework and Classwork Forum and must include the completely filled out template required when posting homework.

This thread is closed.