1

I have a node.js file that accepts an integer arg.

I'm trying to write a bash script that looks for number of available cores and launches main.js for each available core.

For 1 core it should call:

node main.js 3000 &

For 2 cores:

node main.js 3000 &
node main.js 30001 &

And so on...

This is my bash script:

#!/bin/bash
numCores=`getconf _NPROCESSORS_ONLN`
i=0
j=3000
while [ $i < $numCores ]
do
    j=$($j+$i)
    node /myApp/main.js $j &
    i=$($i+1)
done

When I try to run it, I get this error:

bash launchnode.sh
launchnode.sh: line 5: 2: No such file or directory

main.js and launchnode.sh are in the same directory.

Any help?

2
  • 3
    shellcheck.net would have caught this (and a bunch of other bugs) for you automatically. Commented Jan 14, 2017 at 17:53
  • 1
    j=$(($j+$i)) double the parentheses for arithmetic Commented Jan 14, 2017 at 17:53

1 Answer 1

3

The error is here:

while [ $i < $numCores ]

In bash < is for input redirection. [ is an alias for the test command, and test 0 < 2 means "send input from the file named 2 to the command test 0.

Instead, use test's -lt option for a less-than comparison. Also, don't forget to quote your variables:

while [ "$i" -lt "$numCores" ]

Or, if you're only targeting bash, you can use arithmetic expansion:

while (( i < numCores ))

You also need to use double parentheses on subsequent lines for arithmetic:

i=$(($j+$i))
Sign up to request clarification or add additional context in comments.

3 Comments

One problem -- not the only problem. while (( i < numCores )) might be an easier-to-read version if we're only targeting bash, btw. Inside [ ] you should really be quoting your expansions, by the way -- [ "$i" -lt "$numCores" ]; that way if we somehow get an unset variable we have an error that describes that accurately.
Actually, I'd suggest for (( port=3000; port < (3000 + numCores); port++)); do node /myApp/main.js "$port" & done. All the math's inside the C-style for loop's condition, including initialization, comparison and increment.
Good catch @CharlesDuffy. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.