Home > OS >  A shell script to check the version of NodeJS doesn't work in Git Bash on Windows
A shell script to check the version of NodeJS doesn't work in Git Bash on Windows

Time:01-16

I am trying to make a shell script to automatically download, compile and build some program I've made. You can see the full script on my blog. My program requires NodeJS 11 or newer, so I am trying to make my script output an appropriate error message in case it's not installed. Here is what I've tried:

node_version=$(node -v) # This does not seem to work in Git Bash on Windows.
# "node -v" outputs version in the format "v18.12.1"
node_version=${node_version:1} # Remove 'v' at the beginning
node_version=${node_version%\.*} # Remove trailing ".*".
node_version=${node_version%\.*} # Remove trailing ".*".
node_version=$(($node_version)) # Convert the NodeJS version number from a string to an integer.
if [ $node_version -lt 11 ]
then
  echo "NodeJS version is lower than 11 (it is $node_version), you will probably run into trouble!"
fi

However, when I try to run it in Git Bash on Windows 10, with NodeJS 18 installed and in PATH, here is what I get:

stdout is not a tty
NodeJS version is lower than 11 (it is 0), you will probably run into trouble!

What is going on here?

CodePudding user response:

The problem here is a mismatch in expectations of how a terminal should behave from a program with unix/posix expectations compared to how terminals behave on windows. This is a known problem, and there is a longer discussion of the issue on the nodejs repository (although this is not unique to just nodejs).

To compensate there is a tool winpty which provides the missing expectations (or alternatively node-pty), although you normally do not need to install explicitly, it should be included in the normal Git bash installation.

For this reason node is normally set up to be an alias for winpty node, although that causes problems for stout/stdin redirects, so a common practice is to then invoke node as node.exe (e.g. node.exe --help | wc -l) to sometimes avoid using winpty.

For your case you probably want to change your script to

if ...is-running-on-windows... # Check https://stackoverflow.com/q/38086185/23118
then
    # I expect one of these to work
    NODE_BINARY=node.exe
    NODE_BINARY="winpty node"
else
    NODE_BINARY=node
fi
node_version=$($NODE_BINARY -v) 
  • Related