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?

1
  • hmm.. writing programs using the language you know best ... Commented Jun 21, 2011 at 6:16

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

Comments

3

You need to run it using bash executable like this:

 Runtime.getRuntime().exec("/bin/bash -c \"unset DISPLAY\"");

3 Comments

similarly for a windows env it would be cmd instead of /bin/bash -c
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: Indeed, any changes in env variables will only be see by sub shell (child shell) that gets created.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.