Using Command Line Arguments

using nscript function arguments

An nscript function can define command line parameters. Parameters always start with a dollar sign. Based on the names of these parameters the command line arguments of the script will be parsed and parsed to the nscript functions.

Function arguments that do not start with a dollar sign will receive an alias functions for a command with the same name. Built-in functions (like 'cd' or 'run') will take precedence over any system commands.

For example given the following script myscript.js:

#!/usr/bin/nscript
module.exports = function(shell, cp, echo, $verbose, $r, $c, $$changeDir, $args, $1, $2) {
    //code
}

This script can now be invoked, for example, as follows:

./myscript.js --verbose -rc --change-dir src "First Argument"

Based on the name of the parameters, nscript injects values based on the following rules.

  1. The first argument will always be the shell object, regardless the name of that variable.
  2. If a parameter names starts with a dollar sign ($), its value will be true if a similarly named flag was provided to the script. In the example above: if the script was invoked as ./myscript.js --verbose, the $verbose variable will be true in the script.
  3. If a parameter name that starts with a dollar sign is only one character long, short options can be used, for example: ./myscript.js -rc will make both the variables $r and $c true.
  4. If a parameter name starts with a double dollar sign ($$), the value of the variable will hold the value of the specified parameter with which the script was invoked. For example, in ./myscript --change-dir /usr/bin the variable $$changeDir will have the value "/usr/bin"
  5. If the parameter is named $args, it will hold all parameters that where passed to the script that have not been matched by another flag or parameter. For example: ./myscript.js file1.txt -c --change-dir file2.txt file3.txt will yield the value ["file1.txt", "file3.txt"] for $args.
  6. If the parameter is named $0, $1, ..etc, its value will be the value of the specified index in $args, so in the previous example, $2 will have the value "file3.txt".

nscript keeps parameter parsing on purpose quite simple. If you want to have more flexibility; use the commander or yargs packages, they both provide excellent and sophisticated command line arguments parsing.