7

I need to get rid of all the environment variables in a Ksh shell. I can fork a new instance, but it will inevitably source some init files (as far as I know .profile, .kshrc). Is there a way to bypass the sourcing of those files and any other file that might be read at init time?

  • Ksh version: Version M-11/16/88i
  • OS: Solaris 10

Hope I'm clear enough.

rahmu
  • 19,673
  • 28
  • 87
  • 128

2 Answers2

7

~/.profile is only read by login shells. ~/.kshrc is only executed for interactive shells.

Solaris's env supports the syntax (now deprecated, but retained in Solaris, which takes backward compatibility seriously) env - /path/to/command to run /path/to/command in an empty environment. So env - /usr/bin/ksh -c /path/to/script will run the script in an empty environment and will not source any profile script. Ksh might set some environment variables on its own initiative: I don't know about ksh88, but ksh93 sets _ and PWD, and pdksh sets _ and PATH.

You can selectively or indiscriminately clear environment variables from inside ksh.

unset x
for x in $(typeset +x); do
  unset $x
done
Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
  • `env - /path/to/command` is a standard compliant syntax, unless I misunderstand what you means. – jlliagre Nov 02 '11 at 21:59
  • @jlliagre It is? Oh, it [was](http://pubs.opengroup.org/onlinepubs/7990989775/xcu/env.html) but now [it's been withdrawn in favor of `env -i`](http://pubs.opengroup.org/onlinepubs/009695399/utilities/env.html). – Gilles 'SO- stop being evil' Nov 02 '11 at 22:05
  • @Gilles: As usual your explanations are perfect. Is there a way to publicly thank you for everything you've (directly and indirectly) taught me in the course of the past three months? :) – rahmu Nov 02 '11 at 22:34
  • @rahmu Use your newfound knowledge or your knowledge of other topics to provide good answers to other people's questions. Or otherwise [make the Internet a better place](http://xkcd.com/386/). Or otherwise make the world a better place. – Gilles 'SO- stop being evil' Nov 03 '11 at 00:30
5
me@local:~ $ env - /path/to/shell
$ env
_=/usr/bin/env
PATH=/usr/bin:/bin
RANDOM=24395
$

Notes:

  • I used a shell to have a look at the resulting environment, any command can be used (guess what env - /usr/bin/env returns)
  • (@jlliagre's comment:) env is a POSIX standard command.

Edit Clarified the answer.

sr_
  • 15,224
  • 49
  • 55