Java Reference
In-Depth Information
Inline command execution
This feature is usually referred to as “backticks” by seasoned Unix programmers. So,
just as we could write this bit of bash to download content from Google by using the
Unix
curl
command:
echo
"Google says: "
`
curl
http:
//www.google.co.uk`
we can also use the
`
backtick quotes to enclose a Unix shell command that we want
to run from within a Nashorn script. Like this:
print
(
"Google says: "
+
`
curl
http:
//www.google.co.uk`);
String interpolation
String interpolation is a special bit of syntax that allows the programmer to directly
include the contents of a variable without using string concatenation. In Nashorn
scripting, we can use the syntax
${<variable name>}
to interpolate variables within
strings. For example, the previous example of downloading a web page can be
rewritten using interpolation like this:
var
url
=
"www.google.co.uk"
;
var
pageContents
=
`
curl
http:
//${url}`;
print
(
"Google says: ${pageContents}"
);
Special variables
Nashorn also provides several special global variables and functions that are specifi‐
cally helpful for scripting and are not normally available in JavaScript. For example,
the arguments to a script can be accessed via the variable
$ARG
. The arguments must
be passed using the
--
convention, like this:
jjs
test1
.
jjs
--
aa
bbb
cccc
Then the arguments can be accessed as shown in this example:
print
(
$ARG
);
for
(
var
i
=
0
;
i
<
$ARG
.
length
;
i
++)
{
print
(
"${i}: "
+
$ARG
[
i
]);
}
The variable
$ARG
is a JavaScript array (as we can see from
how it behaves when it's passed to
print()
) and needs to be
treated as one. This syntax may be a little confusing for pro‐
grammers coming from other languages, where the
$
symbol
often indicates a scalar variable.