BeanShell Commands Documentation

The following documentation was generated automatically by 'BshDoc' from Javadoc style comments in the BeanShell command script files. See "BshDoc" for more information.

addClassPathvoid addClassPath( string | URL )
bgThread bg( String filename )
bindbind ( bsh .This ths , bsh .NameSpace namespace )
browseClassvoid browseClass( String | Object | Class )
catcat ( String filename )
cat ( URL url )
cat ( InputStream ins )
cat ( Reader reader )
cdvoid cd ( String pathname )
classBrowserclassBrowser ( )
clearclear ( )
cpcp ( String fromFile , String toFile )
debugdebug ( )
desktopvoid desktop()
dirnameString dirname ( String pathname )
editoreditor ( )
errorvoid error ( item )
evalObject eval ( String expression )
execexec ( String arg )
exitexit ( )
extendThis extend( This object )
frameFrame | JFrame | JInternalFrame frame( Component component )
getBshPromptString getBshPrompt ( )
getClassClass getClass ( String name )
getClassPathURL [ ] getClassPath ( )
getResourceURL getResource ( String path )
getSourceFileInfogetSourceFileInfo ( )
importCommandsvoid importCommands( resource path | package name )
javapvoid javap( String | Object | Class | ClassIdentifier )
loadObject load ( String filename )
makeWorkspacemakeWorkspace ( String name )
mvmv ( String fromFile , String toFile )
objectThis object()
pathToFileFile pathToFile ( String filename )
printvoid print ( arg )
printBannerprintBanner ( )
pwdpwd ( )
reloadClassesvoid reloadClasses( [ package name ] )
rmboolean rm ( String pathname )
runrun ( String filename , Object runArgument )
run ( String filename )
savevoid save ( Object obj , String filename )
servervoid server ( int port )
setAccessibilitysetAccessibility ( boolean b )
setClassPathvoid setClassPath( URL [] )
setFontFont setFont ( Component comp , int ptsize )
setNameCompletionvoid setNameCompletion ( boolean bool )
setNameSpacesetNameSpace ( ns )
setStrictJavavoid setStrictJava ( boolean val )
showshow ( )
sourceObject source ( String filename )
Object source ( URL url )
sourceRelativesourceRelative ( String file )
superThis super( String scopename )
unsetvoid unset ( String name )
whichwhich( classIdentifier | string | class )
workspaceEditorworkspaceEditor( bsh.Interpreter parent, String name )

void addClassPath( string | URL )
Add the specified directory or JAR file to the class path. e.g.

    addClassPath( "/home/pat/java/classes" );
    addClassPath( "/home/pat/java/mystuff.jar" );
    addClassPath( new URL("http://myserver/~pat/somebeans.jar") );

See Class Path Management

Thread bg( String filename )
Source a command in its own thread in the caller's namespace

This is like run() except that it runs the command in its own thread. Returns the Thread object control.

bind ( bsh .This ths , bsh .NameSpace namespace )
Bind a bsh object into a particular namespace and interpreter
void browseClass( String | Object | Class )
Open the class browser to view the specified class. If the argument is a string it is considered to be a class name. If the argument is an object, the class of the object is used. If the arg is a class, the class is used.

Note: To browse the String class you can't supply a String. You'd have to do: browseClass( String.class );

cat ( String filename )
cat ( URL url )
cat ( InputStream ins )
cat ( Reader reader )
Print the contents of filename, url, or stream (like Unix cat)
void cd ( String pathname )
Change working directory for dir(), etc. commands (like Unix cd)
classBrowser ( )
Open the class browser.
clear ( )
Clear all variables, methods, and imports from this namespace. If this namespace is the root, it will be reset to the default imports. See NameSpace.clear();
cp ( String fromFile , String toFile )
Copy a file (like Unix cp).
debug ( )
Toggle on and off debug mode. Debug output is verbose and generally useful only for developers.
void desktop()
Start the BeanShell GUI desktop.
String dirname ( String pathname )
Return directory portion of path based on the system default file separator. Note: you should probably use pathToFile() to localize the path relative to BeanShell's working directory and then file.getAbsolutePath() to get back to a system localized string.

Example: to change to the directory that contains the script we're currently executing:

	// Change to the directory containing this script
	path=pathToFile( getSourceFileInfo() ).getAbsolutePath();
	cd( dirname( path ) );
editor ( )
Open a GUI editor from the command line or in the GUI desktop mode. When run from the command line the editor is a simple standalone frame. When run inside the GUI desktop it is a workspace editor. See workspaceEditor()
void error ( item )
Print the item as an error. In the GUI console the text will show up in (something like) red, else it will be printed to standard error.
Object eval ( String expression )
Evaluate the string in the current interpreter (see source()). Returns the result of the evaluation or null.

Evaluate a string as if it were written directly in the current scope, with side effects in the current scope.


    print(b); // 10

eval() acts just like invoked text except that any exceptions generated by the code are captured in a bsh.EvalError. This includes ParseException for syntactic errors and TargetError for exceptions thrown by the evaluated code.


    try {
    } catch ( EvalError e ) {
        // ParseException caught here

    try {
        eval("(Integer)true");  // illegal cast
    } catch ( EvalError e ) {
        // TargetException caught here
        print( e.getTarget() )  // prints ClassCastException

If you want eval() to throw target exceptions directly, without wrapping them, you can simply redefine own eval like so:

    myEval( String expression ) {
        try {
            return eval( expression );
        } catch ( TargetError e ) {
            throw e.getTarget();

Here is a cute example of how to use eval to implement a dynamic cast. i.e. to cast a script to an arbitrary type by name at run-time where the type is not known when you are writing the script. In this case the type is in the variable interfaceType.

    reference = eval( "("+interfaceType+")this" );

Returns the value of the expression.

Throws bsh.EvalError on error

exec ( String arg )
Start an external application using the Java Runtime exec() method. Display any output to the standard BeanShell output using print().
exit ( )
Conditionally exit the virtual machine. Call System.exit(0) unless bsh.system.shutdownOnExit == false.
This extend( This object )
Return a new object that is a child of the specified object. Note: this command will likely change along with a better inheritance mechanism for bsh in a future release.

extend() is like the object() command, which creates a new bsh scripted object, except that the namespace of the new object is a child of the parent object.

For example:


    is equivalent to:
    foo() { 
        bar() {
            return this; 


    and also:
    ar.namespace.bind( foo.namespace );

The last example above is exactly what the extend() command does. In each case the bar object inherits variables from foo in the usual way.

Frame | JFrame | JInternalFrame frame( Component component )
Show component in a frame, centered and packed, handling disposal with the close button.

Display the component, centered and packed, in a Frame, JFrame, or JInternalFrame. Returns the frame. If the GUI desktop is running then a JInternaFrame will be used and automatically added to the desktop. Otherwise if Swing is available a top level JFrame will be created. Otherwise a plain AWT Frame will be created.

String getBshPrompt ( )
Get the value to display for the bsh interactive prompt. This command checks for the variable bsh.prompt and uses it if set. else returns "bsh % "

Remember that you can override bsh commands simply by defining the method in your namespace. e.g. the following method displays the current working directory in your prompt:

	String getBshPrompt() {
		return bsh.cwd + " % ";
Class getClass ( String name )
Get a class through the current namespace utilizing the current imports, extended classloader, etc.

This is equivalent to the standard Class.forName() method for class loading, however it takes advantage of the BeanShell class manager so that added classpath will be taken into account. You can also use Class.forName(), however if you have modified the classpath or reloaded classes from within your script the modifications will only appear if you use the getClass() command.

URL [ ] getClassPath ( )
Get the current classpath including all user path, extended path, and the bootstrap JAR file if possible.
URL getResource ( String path )
Get a resource from the BeanShell classpath. This method takes into account modification to the BeanShell class path via addClassPath() and setClassPath();
getSourceFileInfo ( )
Return the name of the file or source from which the current interpreter is reading. Note that if you use this within a method, the result will not be the file from which the method was sourced, but will be the file that the caller of the method is reading. Methods are sourced once but can be called many times... Each time the interpreter may be associated with a different file and it is that calling interpreter that you are asking for information.

Note: although it may seems like this command would always return the getSourceFileInfo.bsh file, it does not since it is being executed after sourcing by the caller's interpreter. If one wanted to know the file from which a bsh method was sourced one would have to either capture that info when the file was sourced (by saving the state of the getSourceFileInfo() in a variable outside of the method or more generally we could add the info to the BshMethod class so that bsh methods remember from what source they were created...

void importCommands( resource path | package name )
Import scripted or compiled BeanShell commands in the following package in the classpath. You may use either "/" path or "." package notation. e.g.
		// equivalent

	When searching for a command each path will be checked for first, a file
	named 'command'.bsh and second a class file named 'command'.class.

You may add to the BeanShell classpath using the addClassPath() or setClassPath() commands and then import them as usual.


If a relative path style specifier is used then it is made into an absolute path by prepending "/". Later imports take precedence over earlier ones.

Imported commands are scoped just like imported clases.

void javap( String | Object | Class | ClassIdentifier )
Print the public fields and methods of the specified class (output similar to the JDK javap command).

If the argument is a string it is considered to be a class name. If the argument is an object, the class of the object is used. If the arg is a class, the class is used. If the argument is a class identifier, the class identified by the class identifier will be used. e.g. If the argument is the empty string an error will be printed.

	// equivalent
	javap( java.util.Date ); // class identifier
	javap( java.util.Date.class ); // class
	javap( "java.util.Date" ); // String name of class
	javap( new java.util.Date() ); // instance of class
Object load ( String filename )
Load a serialized Java object from filename. Returns the object.
makeWorkspace ( String name )
Open a new workspace (JConsole) in the GUI desktop.
mv ( String fromFile , String toFile )
Rename a file (like Unix mv).
This object()
Return an "empty" BeanShell object context which can be used to hold data items. e.g.

    myStuff = object();
    myStuff.foo = 42;
    myStuff.bar = "blah";
File pathToFile ( String filename )
Create a File object corresponding to the specified file path name, taking into account the bsh current working directory (bsh.cwd)
void print ( arg )
Print the string value of the argument, which may be of any type. If beanshell is running interactively, the output will always go to the command line, otherwise it will go to System.out.

Most often the printed value of an object will simply be the Java toString() of the object. However if the argument is an array the contents of the array will be (recursively) listed in a verbose way.

Note that you are always free to use System.out.println() instead of print().

printBanner ( )
Print the BeanShell banner (version and author line) - GUI or non GUI.
pwd ( )
Print the BeanShell working directory. This is the cwd obeyed by all the unix-like bsh commands.
void reloadClasses( [ package name ] )
Reload the specified class, package name, or all classes if no name is given. e.g.

    reloadClasses(".*")  // reload unpackaged classes

See "Class Path Management"

boolean rm ( String pathname )
Remove a file (like Unix rm).
run ( String filename , Object runArgument )
run ( String filename )
Run a command in its own in its own private global namespace, with its own class manager and interpeter context. (kind of like unix "chroot" for a namespace). The root bsh system object is extended (with the extend() command) and made visible here, so that general system info (e.g. current working directory) is effectively inherited. Because the root bsh object is extended it is effectively read only / copy on write... e.g. you can change directories in the child context, do imports, change the classpath, etc. and it will not affect the calling context.

run() is like source() except that it runs the command in a new, subordinate and prune()'d namespace. So it's like "running" a command instead of "sourcing" it. run() teturns the object context in which the command was run.

Returns the object context so that you can gather results.

Parameter runArgument an argument passed to the child context under the name runArgument. e.g. you might pass in the calling This context from which to draw variables, etc.

void save ( Object obj , String filename )
Save a serializable Java object to filename.
void server ( int port )
Create a remote BeanShell listener service attached to the current interpreter, listening on the specified port.
setAccessibility ( boolean b )
Setting accessibility on enables to private and other non-public fields and method.
void setClassPath( URL [] )
Change the classpath to the specified array of directories and/or archives.

See "Class Path Management" for details.

Font setFont ( Component comp , int ptsize )
Change the point size of the font on the specified component, to ptsize. This is just a convenience for playing with GUI components.
void setNameCompletion ( boolean bool )
Allow users to turn off name completion.

Turn name completion in the GUI console on or off. Name competion is on by default. Explicitly setting it to true however can be used to prompt bsh to read the classpath and provide immediate feedback. (Otherwise this may happen behind the scenes the first time name completion is attempted). Setting it to false will disable name completion.

setNameSpace ( ns )
Set the namespace (context) of the current scope.

The following example illustrates swapping the current namespace.

    fooState = object(); 
    barState = object(); 
    print(a);  // 5
    print(a); // 6

You could use this to creates the effect of a static namespace for a method by explicitly setting the namespace upon entry.

void setStrictJava ( boolean val )
Enable or disable "Strict Java Mode". When strict Java mode is enabled BeanShell will:

  1. Require typed variable declarations, method arguments and return types.
  2. Modify the scoping of variables to look for the variable declaration first in the parent namespace, as in a java method inside a java class. e.g. if you can write a method called incrementFoo() that will do the expected thing without referring to "super.foo".

    See "Strict Java Mode" for more details.

    Note: Currently most standard BeanShell commands will not work in Strict Java mode simply because they have not been written with full types, etc.

show ( )
Toggle on or off displaying the results of expressions (off by default). When show mode is on bsh will print() the value returned by each expression you type on the command line.
Object source ( String filename )
Object source ( URL url )
Read filename into the interpreter and evaluate it in the current namespace. Like the Bourne Shell "." command. This command acts exactly like the eval() command but reads from a file or URL source.
sourceRelative ( String file )
Source a file relative to the callering script's directory.

e.g. scripts A running in dir A sources script B in dir B. Script B can use this command to load additional scripts (data, etc.) relative to its own location (dir B) without having to explicitly know its "home" directory (B).

Note: this only works for files currently.

This super( String scopename )
Return a BeanShell 'this' reference to the enclosing scope (method scope) of the specified name. e.g.

    foo() {
        bar() {
            gee() {
                print( x ); // 3
                print( super.x ); // 2
                print( super("foo").x ); // 1

This is an experimental command that is not intended to be of general use.

void unset ( String name )
"Undefine" the variable specifed by 'name' (So that it tests == void).

Note: there will be a better way to do this in the future. This is currently equivalent to doing namespace.setVariable(name, null);

which( classIdentifier | string | class )
Use classpath mapping to determine the source of the specified class file. (Like the Unix which command for executables).

This command maps the entire classpath and prints all of the occurrences of the class. If you just want to find the first occurrence in the classpath (the one that will be used by Java) you can also get it by printing the URL of the resource. e.g.:

        print( getResource("/com/foo/MyClass.class") );
		// Same as...
        // System.out.println(
        //    getClass().getResourceAsStream("/com/foo/MyClass.class" ) );

Note: This is all a lie! This command is broken and only reports the currently first occurence! To be fixed!

workspaceEditor( bsh.Interpreter parent, String name )
Make a new workspaceEditor in the GUI.