Accessing arguments and environment variables

Accessing arguments and environment variables

JXA scripts can access command line parameters and environment variables through NSProcessInfo properties.

Retrieving command line arguments#

As described in the introduction, you can [run JXA scripts directly from the terminal](https://bru6.de/jxa/introduction-to-jxa/#Running scripts) by adding #!/usr/bin/osascript -l JavaScript as first line to the code. With ObjC, it is straightforward to get any arguments you pass on the command line:

ObjC.import("Foundation");
const args = $.NSProcessInfo.processInfo.arguments;
// args[0..3] are filename, "/usr/bin/osascript", "-l", "JavaScript"
if (args.count > 4) {
  var firstArgument = args.js[4].js; // firstArgument is a string!
  …
}
Take notice of the different environments here. args is an NSArray whose property count reflects the number of items. To get at a single item in JavaScript, you must convert args to a JavaScript array by calling its method js. Therefore, args.js[4] returns the fifth element of args in JavaScript. However, all elements of args are NSStrings. To obtain a JavaScript string, you must again call js on this fifth element.

Accessing environment variables#

Access to environment variables might be useful for example if you want to get the absolute path of your current working directory:

ObjC.import("Foundation");
const environment = $.NSProcessInfo.processInfo.environment.js;
const currentDir = 'PWD' in environment ? environment.PWD.js : undefined;

Here, processInfo.environment returns an NSDictionary object. It is converted to a JavaScript object by calling its js method. The PWD property of this object contains the current directory as an NSString object. To convert it to a JavaScript string, you have to call js again. It is wise to check for the existence of the variable in the environment dictionary with in first – omitting that check will throw an exception if you try to convert the variable’s value to a JavaScript string.

Occasionally, you’ll see that $.getenv() from the Standard C library is used to inquire the environment. You should not do this, since getenv() throws an exception if the variable you’re looking for is not defined.