dreamsys software

JavaScript Shell Scripting Tutorial

Functions


When your scripts start to become very large, you may tend to notice that you are repeating code more often in your scripts. You have the ability to create functions inside of your script to help with code reuse. Writing the same code in multiple sections of your script can lead to severe maintenance problems. When you fix a bug in a section of code you need to be sure that all sections of code that are repeated will also have those fixes. A function is a block of code that can be called from other parts of your script. It can have parameters passed to it as if it were a separate script itself. As an example, we will create a function called logit, which will take two parameters, a level and a message. The level will be a number between 1 and 3 that will indicate the severity of the log message. The level of messages that you want to view will be passed in the command line of the script.

#!/usr/bin/env node

var args = process.argv.slice(2);

var logLevel = args[0];

var logit = function(level, msg) {
        if (level >= logLevel) {
                console.log('MSG ' + level + ': ' + msg);
        }
}

var getUser = function() {
        logit(2, 'Entering Function getUser()...');
        var userName = args[1];
        logit(1, 'Leaving Function getUser()...');
        return userName;
}

logit(3, 'Starting Script...');
logit(3, 'Got User: ' + getUser());
logit(3, 'Exiting Script');

In this script, we are using 3 different numbers for log levels. 3 is like an INFO level, 2 is like a DEBUG level and 1 is like a TRACE level, to see the most log detail possible. The log level and user name are to be used is passed as the parameter to the script for simplicity. Let's save this file as logit.js and run it several times with different input levels...

$ ./logit.js 1 asdf
MSG 3: Starting Script...
MSG 2: Entering Function getUser()...
MSG 1: Leaving Function getUser()...
MSG 3: Got User: asdf
MSG 3: Exiting Script
$ ./logit.js 2 asdf
MSG 3: Starting Script...
MSG 2: Entering Function getUser()...
MSG 3: Got User: asdf
MSG 3: Exiting Script
$ ./logit.js 3 asdf
MSG 3: Starting Script...
MSG 3: Got User: asdf
MSG 3: Exiting Script

The script creates two functions, one for logging and another to get the user name input from the command line parameter. Notice that we use the function keyword to define a function, and the syntax is very simple. After the function keyword, you give the parameters to the function. The parameters are accessed in the function just as local variables. The curly braces define where the function starts and ends, just as it does with if/else and looping blocks.

You will also notice that one function has a return value and the other doesn't. You don't need to define the return value in the definition of the function, you just need to use the return keyword in the function for it to return a value.

You can write recursive functions in JavaScript as well. Consider the factoral:

#!/usr/bin/env node

var fac = function(n) {
	if (n > 1) {
		return n * fac(n - 1);
	} else {
		return 1;
	}
}

var args = process.argv.slice(2);
var num = args[0];

console.log(num + '! = ' + fac(num));

A recursive function is a function that calls itself. Notice at line 5 in the script, it calls the fac function inside itself. Recursive functions have the possibility of going in an endless loop and crashing if you do not code them right, so only use a recursive function if you really understand what you are trying to do.

Now that you know about functions, you can learn how to organize them into logical units with classes.

Prev (Looping) | Next (Classes)


Blog Entries
Blob Entry 1
Blob Entry 2
Blob Entry 3
Blob Entry 4
Blob Entry 5
Blob Entry 6