Keilly: Use the command line (to read/write files and other fun stuff)

Saturday, June 2, 2007

Use the command line (to read/write files and other fun stuff)

Using the command line from a widget adds the ability to make widgets much more powerful than standard web pages. It's really easy to do by using the widget.system call.

e.g., to run a script (drag the script to your widget 'Files' section):
  widget.system("./", null);
Simple write to file 'data.txt'"
  widget.system("/bin/echo Some data >> data.txt", null);
widget.system("/bin/echo More data >> data.txt", null);
Simple file read from 'data.txt':
  var data =
widget.system("/bin/cat data.txt ", null).outputString;
Run a java application:
  widget.system("/usr/bin/java ", null)
Note the use of the path to the executable in the system call. Looks like the widget doesn't have a good path variable set up in it's shell. Not sure why, but it's easy enough to find an executable location by typing 'which java' in Terminal.

Make sure that the widget has the attribute 'Allow Command Line Access' turned on or instead you'll get a non obvious exception when executing the system call.


Anonymous said...

People should read this.

Unknown said...

How can I use "echo" to read the HOME environment variable?

Neil Cochrane said...

Looks like env is what you need:
will fetch all environment variables.

To only show a particular env variable pass the result to grep. e.g. for the DISPLAY enviroment variable:

"/usr/bin/env | /usr/bin/grep ^DISPLAY"

The ^ character ensures that DISPLAY is matched at the start of a line.

Neil Cochrane said...

I suppose you could also use the ~ character as this is interpreted as the users home directory.
Change directory to the curernt users home:
cd ~

or change directory to a specific users home:
cd ~mike