2 System Scripting
You can do a lot of scripting of the Linux system in PLT Scheme. I prefer it infinitely to using Bash (bash), C Shell (tcsh), or any other *NIX shell for that matter. The reason is simple: Scheme is more powerful, better defined, and I’m less likely to screw up and delete half of my home directory. These all, for me, are good reasons to write my shell scripts in Scheme.
Choose one of the two following exercises. They’ll each introduce you to something new in Scheme.
2.1 Traversing the filesystem
I’d like to know how big my home directory is. There are ways I could do this on the command line, but why use a single UNIX command when I could write a script, right? (Wrong, but just agree for the moment.)
PLT Scheme gives us a bunch of tools for interacting with the filesystem. You can write a function that walks through my home directory using the following tools:
directory-list
file-exists?
directory-exists?
build-path
I had 18 lines of code, including whitespace. The template for my code looked like this:
| (define (calc path) |
| (calc-size path (directory-list path))) |
| (define (calc-size current-path dir-ls) |
| ....) |
When I was done, I was able to use the function calc as follows:
| > (calc "/Users/jadudm/Music") |
11168925092 |
Like many problems, if you clearly understand the structure of the data, the solution should present itself. Directory hierarchies are trees, so the solution to this problem should look very much like the kind of code you’ve written a lot of this semester.
2.2 If you want...
If you knock that down, you could pretty it up a bit. I’d rather the result came back in a more human-readable form.
| > (usage "/Users/jadudm/Music") |
"11G 168M 925K" |
2.3 Handling the command line
I’d say more, but I’m exhausted.
Take a look in the documentation for the scheme/cmdline library. There is quite a bit there, so I’ve provided a starter file:
| (require scheme/cmdline) |
| (define say-hello |
| (command-line |
| #:program "hello" |
| #:once-each |
| [("-n" "--name") name |
| "Say hello to someone." |
| (printf "Hi there, ~a!~n" name)])) |
| say-hello |
Save that to “hello.ss”. Then, on the command-line, run:
mzscheme hello.ss
That will seem to do nothing. So, add a flag:
mzscheme hello.ss -h
That will tell you how to use your script.
If you’d like to compile your program, try typing:
mzc --exe hello hello.ss
Then, you should be able to say:
./hello -h
to run the program. You’ve now written and compiled Scheme program that takes command-line arguments. Tie this together with the previous exercise, and you have a program that you can use to get the size of any directory.
2.4 What else?
If you look in the documentation for system, you’ll find out how to spawn new processes, and probably a whole bunch more as well. Fun fun!