2
\$\begingroup\$

I am solving an exercise. Essentially, it's a shell script that takes in file and/or directory arguments and outputs another (standalone) shell script that outputs these files, including any directory structure associated with them.

Example usage:

bundle.sh dir1 dir2 file1 file2 file3 >unpack.sh

This expects that bundle.sh can be found in the PATH environment variable. If not, just run it like this:

`pwd`/bundle.sh dir file1 file2 >unpack.sh

Running unpack.sh should recreate everything.

Accepted limitations:

  • Only works for textual files
  • Files may not contain the line End of filename

Solution:

echo "# Run to unpack"
for i; do
    (cd $i 2>/dev/null &&
     echo "mkdir $i && cd $i" &&
     $0 * &&
     echo cd ..)
    cd $i 2>/dev/null || (
        echo echo `ls -l $i`
        echo "cat >$i <<'End of $i'"
        cat $i
        echo End of $i)
done

This is my solution for exercises 3-17 and 3-18 in the Unix Programming Environment by Brian W. Kernighan and Rob Pike. It works but I would appreciate any feedback. I will mention that the book has not yet covered conditional statements, globbing, etc. So I am trying to stick to what I've learned so far for now and might come back to it later.

One thing that I realize is that this doesn't deal with names that contain spaces. I have tried putting \"s around most $is (except for the ones in the echos, where it shouldn't matter) but that seems to make things worse. The other two is that I find my usage of cd to test for directories kind of a hack and the fact that I am not sure I am handling $0 correctly, which is why I made explicit requirements on how to run bundle.sh (maybe there is some way to make it better?). However, I am not interested in just these issues, I want feedback in general given my requirements and constraints. Even advice regarding to style may be valuable to me.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.