3

How can I find the user's shell (bash, zsh etc) where the current Node.js process is running?

Is it possible to find it without running a child process (like this, for example)?

ps -p $$
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474

1 Answers1

6

process.env.SHELL should provide you with the path to the user's shell.

robertklep
  • 198,204
  • 35
  • 394
  • 381
  • 3
    I did try it in `zsh` environment but it still outputs `/bin/bash`... However, `echo $0` outputs `zsh`. – Ionică Bizău Aug 23 '15 at 14:21
  • Since it's an environment variable, it _is_ possible to overwrite. I use the zsh as well, and for me it contains `/bin/zsh` as expected. You should make sure that you're not loading a (system) configuration file that mistakenly sets it to `/bin/bash` (and that `zsh` is your actual shell: `getent passwd $LOGNAME`) – robertklep Aug 23 '15 at 14:54
  • 2
    We can check for the `ZSH_VERSION` variable: `var shell = process.env.ZSH_VERSION ? "zsh" : process.env.SHELL`. That doesn't/shouldn't exist in non-zsh environments. – Ionică Bizău Jun 01 '16 at 07:15
  • `process.env.shell` is absolutely NOT the correct answer. That returns the path to the _default_ shell not the _current_ shell. More details in this answer https://stackoverflow.com/questions/3327013/how-to-determine-the-current-interactive-shell-that-im-in-command-line alas, i dunno what the _right_ answer is in node-land. – masukomi Jul 01 '22 at 21:20
  • @masukomi with "the user's shell" I meant their configured (default) shell. There's also [`os.userInfo().shell`](https://nodejs.org/api/os.html#osuserinfooptions), which also returns the configured shell. – robertklep Jul 02 '22 at 06:56
  • sure @robertklep but the question is the user's "CURRENT" shell, and your answer does not note that it's an answer for the very different question of what their DEFUALT shell is. This leads folks, like the devs of Heroku's CLI, to use code which breaks when users are using a different shell than their default. – masukomi Jul 12 '22 at 16:29
  • @masukomi I guess we interpret the original question differently, but if it's meant as "the current interactive shell" then yes, `process.env.SHELL` isn't correct for all situations (I would guess it will work in 99.9% of the cases, though). Sadly, there's no real alternative other than some convoluted heuristics. Or a user should just learn how to change their interactive shell ;) (and yes, I realise this isn't always possible) – robertklep Jul 12 '22 at 17:08