Table of Contents

  1. (Python)
  2. (Perl)
  3. (Scheme)
  4. (Clojure)
  5. Conclusion

Call Program Like A Function

Posted on 18 Dec 2012, tagged shellformal language

What’s the most important application for Linux users? The answer must be shell. It comes out the ability to combine tools together to solve complex problem. It is a little like function, such as A | B could be represented as A(B(x)). But how do you respresent the format A(B(x), C(y)) in a shell?

So here comes some libraries to call command like a function in programming languages. They are interesting, but you may not want to use them in a real project. Let’s take a look first and then we will talk about them.

Sh (Python)

This library contains many advanced features and is well documented.

1# sort this directory by biggest file
2print(sort(du(glob("*"), "-sb"), "-rn"))
4# print(the number of folders and files in /etc
5print(wc(ls("/etc", "-1"), "-l")))

Shell (Perl)

Using perl with shell command is always comfortable.

1use Shell qw(cat ps cp);
3$passwd = cat('</etc/passwd');
4@pslines = ps('-ww'),
5cp("/etc/passwd", "/tmp/passwd");
6# object oriented
7my $sh = Shell->new;
8print $sh->ls('-l');

Scsh (Scheme)

Scheme is a great and purl language. But scsh seems like a dead project. You can find a fork on github. Howerver, I failed to compile its dependency scheme48.

Shake (Clojure)

It is written by one of my old colleagues. It has a discuss on Hacker News.

 1(require '[shake.static :as sh])
 3;; any shell command ...
 4(sh/uname -a) ;;returns a #<UNIXProcess java.lang.UNIXProcess@1833160>
 6;; using clojure variables (vars, local bindings) in shake
 7(let [home "/home/sunng87"]
 8  (sh/ls -l $home))
10;; using clojure forms in shake
11(sh/curl $(format "" "sunng87"))


So after all, you may ask: why not just use these language’s REPL as a shell? It provides more power! But thinking of the daily life on Linux, how many times will you use these “advance features”? Instead, if you prefer the “function style shell”, you need to type many parentheses, quotes and so on. I think the current shell may not provides the most complete ability, but it provides the most efficient way to work.

comments powered by Disqus