Hacker News new | ask | show | jobs
by nsomaru 3363 days ago
Care to document some of those insights for those of us in a similar position?
1 comments

Here are a couple of thoughts:

- I used to spend a lot of time stuffing things into variables and then trying to operate on those, which is how you do things in imperative languages. Shell is better thought of in dataflow terms, i.e. pipelines. So I started using pipelines more and more.

- The corollary is that you start thinking more about data (passing between pipeline stages) and less about control flow.

- Compare an if statement in C, for example, to an if statement in a functional language. In C an if statement has no value per se, but in functional languages if "statements" are actually expressions that have a value:

f :: A -> String f x = if isFoo x then "foo" else "other"

In shell an if statement is just another command, so you can do things with its "value", i.e. its stdout:

    if do_test
    then
        cat file1.txt
    else
        cat file2.txt
    fi | grep pattern
Because I was so used to thinking of if statements as just control flow, I never used to think of piping them to another command like that.

Also if you think carefully, that last pipe to "grep pattern" has the flavour of partial evaluation in functional programming.

- I tend to think more in terms of building up an execution environment these days, in the same way that lexical scope works in regular programming languages. In shell, of course, that means command invocations, sub-shells, etc., because the shell doesn't really have good lexical scoping. The simplest example I can think of is executing some commands in another working directory with a sub-shell:

    (
        cd $dir
        run_test > "${f}.log"
    )
You could compare it to RAII in C++ or with- style macros like WITH-OPEN-FILE in Common Lisp.

Those are just some examples.

EDIT: Also, have a read of the links in chubot's post: https://news.ycombinator.com/item?id=14012453 . That's the sort of mentality that will change your approach to shell programming.