In Using environment variables in JBoss CLI, we described how to pass environment variables to CLI scripts. This brings us to a related concept – not unlike Unix shells, CLI also allows us to define variables for use inside scripts and interactive sessions.

The basic commands for defining and undefining variables are set and unset, respectively. The $ symbol can be used to reference a variable, and its value can be printed using the echo command. In general, tho whole system is very similar to what we’re used to from standard Unix shells, so an example should be enough to explain the basic concepts:

[standalone@localhost:9990 /] set FOO=bar
[standalone@localhost:9990 /] echo $FOO
bar
[standalone@localhost:9990 /] unset FOO
[standalone@localhost:9990 /] echo $FOO
Unrecognized variable FOO

Multiple variables can be managed in a single command, such as:

[standalone@localhost:9990 /] set GREETING=hello OBJECT=world
[standalone@localhost:9990 /] echo $GREETING $OBJECT
hello world
[standalone@localhost:9990 /] unset GREETING OBJECT

Using set without arguments prints all the variable assignments:

[standalone@localhost:9990 /] set GREETING=hello OBJECT=world
[standalone@localhost:9990 /] set
GREETING=hello
OBJECT=world

The system is relatively versatile – variables can refer to various things, including operations, commands, parameters, values etc. For example:

[standalone@localhost:9990 /] set PROPERTY=/system-property OPERATION=add \
PROPERTY_NAME=foo PARAMETER_NAME=value PARAMETER_VALUE=bar
[standalone@localhost:9990 /] $PROPERTY=$PROPERTY_NAME:\
$OPERATION($PARAMETER_NAME=$PARAMETER_VALUE)
{"outcome" => "success"}
[standalone@localhost:9990 /] $PROPERTY=$PROPERTY_NAME:read-resource
{
"outcome" => "success",
"result" => {"value" => "bar"}
}
[standalone@localhost:9990 /] $PROPERTY=$PROPERTY_NAME:remove
{"outcome" => "success"}
[standalone@localhost:9990 /] set COMMAND=$PROPERTY=$PROPERTY_NAME:$OPERATION($PARAMETER_NAME=$PARAMETER_VALUE)
[standalone@localhost:9990 /] $COMMAND
{"outcome" => "success"}
[standalone@localhost:9990 /] $PROPERTY=$PROPERTY_NAME:read-resource
{
"outcome" => "success",
"result" => {"value" => "bar"}
}

Note that the scope of variables is, similarly to Bash and other Unix shells, tied to a session. If you quit the session which you defined the variables in and relaunch the CLI, variable assignments will be lost. Similarly, if a variable is set in a script, it will be undefined in a different script executed via a separate invocation of the CLI.