[SOLVED] What is the correct syntax for executing bash script in a shebang executing in a non login shell

Issue

This Content is from Stack Overflow. Question asked by Preet Sangha

The shebang for a node script in the login shell is:

#!/usr/bin/env node   

This doesn’t work for non-login shell so I want to do the equivalent of:

#!/usr/bin/env [[ -s $HOME/.nvm/nvm.sh ]] && source "$HOME/.nvm/nvm.sh" && node

But I’m not able to get the syntax correct. I’ve tried several ways, including quoting the script or trying to run it bash -c. BUt each time I’m facing parsing errors



Solution

The shebang is not well suited to running complex commands. It’s job is just to tell the kernel what interpreter you want to use for the script. It’s not executed in your shell, so concepts like [[ or && or even $parameter won’t exist. In your error messages, env is telling you it wants a command it can find on your path and [[ is a bash keyword so that won’t work.

The standard solution if you need to do some setup before running your command is a wrapper script, like Julien suggested.

#!/usr/bin/env bash
[[ -s $HOME/.nvm/nvm.sh ]] && source "$HOME/.nvm/nvm.sh" && node bin/nodesample.js

You could even go one step further and install a wrapper script that you can then use on the shebang line of other node scripts.

#!/usr/bin/env bash
# nodewrapper script - place in e.g. /bin
[[ -s $HOME/.nvm/nvm.sh ]] && source "$HOME/.nvm/nvm.sh" && exec node "${@}"
#!/bin/nodewrapper
const semver = require('semver');
console.log("Hello World! You're using " + process.version)


This Question was asked in StackOverflow by Preet Sangha and Answered by tjm3772 It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?