tags:

views:

452

answers:

2

I know this is lame way to do it. We need to capture a string that is dynamically generated in a Java program in the calling shell script and then use it later.

Also this is to be done in an existing csh file.

We considered the option of exporting it to an environment variable using putenv/setenv ... is that a better option? If so how to use it?

There seems to be lack of example code on net on how to effectively use sentenv() or putenv() and what libraries to import for the same.

System class that has the getenv() method does not show my putenv() or setenv(). Any help is highly appreciated.

Thanks.

+2  A: 

You should be able to just use command substitution, using backtick syntax just as in bash (in bash nowadays, the more usable $-syntax is recommended). Like so:

$ set A=`java MyProgram`
$ echo $A

or something very similar

You cannot use the environment; it's not possible to communicate "backwards" using it; a child process cannot change the parent's environment.

UPDATED: Added the 'set' keyword in the example, d'oh.

unwind
I am using a csh ... would A=`java MyProgram` work OR I need to use set A = `java MyProgram`
Devang Kamdar
When I am using A=`java MyProgram` ... its giving me A: Command not found
Devang Kamdar
@Devang: correct, for csh you need to explicitly use 'set', I changed the example. Sorry.
unwind
@unwind: Thanks ... but I tried and its still not returning anything. Infact I have a line that simply calls the java program. Since the there is a System.out.println(), I should see some output, but I am not seeing anyting. When i run the program from command line, it runs perfectly fine. Not sure what am I missing. Is there a specific way to call java from csh? Its working in a ksh file correctly ... cursing the legacy csh script right now :)
Devang Kamdar
Hey its working ... I was overlooking some silly stuff ... was not giving the command line argument to Java program correctly inside the shell script. Thanks for your help though.
Devang Kamdar
A: 

Extending from the first answer:

You probably want to do this: $ A=java MyProgram | grep <something> $ echo $A

where is what you like to capture, assuming the MyProgram output more than one line.

If the java program uses System.err.print...instead of System.out.print.... you need to enhanced to $ A=java MyProgram 2>&1 | grep <something>

hope it helps :-)

SS
Actually I need the whole result ... dont really need to grep ... also my pain-point right now it to make it work in a csh script. It works fine in a ksh ... but csh is giving me either strange errors or returning nothing ... thanks for your help.
Devang Kamdar