0

I want to run unset DISPLAY as a command in the linux terminal, using a Java program.

I tried using Runtime.getRuntime().exec("unset DISPLAY");, but it doesn't work.

What could I do here?

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
Harinder
  • 11,776
  • 16
  • 70
  • 126

2 Answers2

6

This won't work, and here's why. Environment variables are inherited from the parent process. A child can't control a parent's environment. Here's what's happening in your setup:

 bash   ->   java   ->   unset
   |           |           |
 parent      child     grand-child
   |           |           |
unaffected unaffected   affected

So in actuality your command IS working, however it's not having the effect you want it to. Sadly java won't be able to change the parent's environment.

Your java program can modify environment variables of its own, and any children spawned by java will inherit those variables. So you could potentially have java launch a bash shell for you, and then use that bash shell interactively, but that seems like a lot of overhead.

See this post for how to set java's environment variables:
How do I set environment variables from Java?

If you're willing to sidestep the whole java problem, what most people do in this situation is source a special file. For example, create a file called "no-x.sh" that looks like this:

# Unset the display variable
unset DISPLAY

And then from your current (interactive) shell, source the file like this:

$> source no-x.sh

and now your main bash shell has had its environment changed. Note that this is a HACK (or for all of you bash zealots out there -- a feature) and you should never expect to duplicate this functionality with anything else (like java).

Community
  • 1
  • 1
Chris Eberle
  • 47,994
  • 12
  • 82
  • 119
3

You need to run it using bash executable like this:

 Runtime.getRuntime().exec("/bin/bash -c \"unset DISPLAY\"");
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    similarly for a windows env it would be cmd instead of /bin/bash -c – GoodSp33d Jun 21 '11 at 04:20
  • But still it should be noted that a simple `unset DISPLAY` will not effect anything after the bash (or cmd or ...) process exits, see Chris's answer. – Paŭlo Ebermann Jun 26 '11 at 21:16
  • @Paŭlo Ebermann: Indeed, any changes in env variables will only be see by sub shell (child shell) that gets created. – anubhava Jun 27 '11 at 12:27