Write a function

November 3rd, 2006 toydi Posted in Common, dot, function | Hits: 21940 | 4 Comments »

To write a function, choose a syntax you prefer, either:

function funct-name { commands; }

or:

funct-name() { commands; }

and remember two things:

  • use spaces to separate curly braces from commands,
  • commands must end in a semicolon or newline.

Let’s try!

In a previous post, I used sort and uniq to emulate a few set theory operations. This time, I try to write them as functions:

union() { sort -u $1 $2; }

intersect() { sort $1 $2 | uniq -d; }

sym-diff() {
sort $1 $2 | uniq -d
}

function rel-compl {
sort $1 $2 | uniq -d | sort $1 - | uniq -u
}

Save them into a text file, setheory-functions and load it into my current shell using dot command:

. setheory-functions

Finally, to run a function, e.g. union :

union aquatic mammal

Both aquatic and mammal will be sent into the function as argument $1 and $2, respectively.

4 Responses to “Write a function”

  1. . is Bash Buildin, its like source

    source setheory-functions

    Do this, have the same effect.

  2. . and source should be the same. Read `man source`.

  3. Hi, your symmetric difference should be `uniq -u`
    Also some attribution would be nice:
    http://www.pixelbeat.org/cmdline.html#sets

    cheers,
    Pádraig.

  4. Just about all of what you mention happens to be astonishingly precise and it makes me wonder why I hadn’t looked at this with this light before. Your article truly did turn the light on for me personally as far as this particular topic goes. Arizona Family Dental, 590 N Alma School Rd #5, Chandler AZ 85224

Leave a Reply