This will not work at all:
var myscript = exec('sh ./scripts/mongo-backup.sh',+ dbname );
because it tries to make a number from the dbname (the unary plus operator) which most likely results in NaN and then it passes is as the second argument to exec (which should be an optional options object).
What you probably meant is:
var myscript = exec('sh ./scripts/mongo-backup.sh ' + dbname);
Another thing to note is that your script is declared as a Bash script and you are explicitly running it with sh and not bash. The sh command on some system can be not compatible with Bash - e.g. sometimes it is Dash or some other simple shell, so this is better:
var myscript = exec('bash ./scripts/mongo-backup.sh ' + dbname);
This will pass it as an argument to the script which you will be able to access as $1 in the shell script:
#!/bin/bash
echo $1
or similar to your example:
#!/bin/bash
MONGO_DATABASE=$1
# use $MONGO_DATABASE as you need
You can do a similar thing with spawn without using string concatenation:
var myscript = spawn('bash', ['./scripts/mongo-backup.sh', dbname]);
This will not break when you have some character in dbname that would be misinterpreted by the shell as some special character. This is not likely but needs to be considered.
You can also pass your variables as environment variables to your shell script, so that you can use a named variables directly. For example:
var env = Object.assign({}, process.env, { dbname });
var myscript = spawn('bash', ['./scripts/mongo-backup.sh'], { env });
And now you can just use $dbname in your shell script, for example:
#!/bin/bash
echo $dbname
or similar to your example:
#!/bin/bash
MONGO_DATABASE=$dbname
# use $MONGO_DATABASE as you need
You can also pass the MONGO_DATABASE directly:
var env = Object.assign({}, process.env, { MONGO_DATABASE: dbname });
var myscript = spawn('bash', ['./scripts/mongo-backup.sh'], { env });
and just use it in your script with no other variables needed:
#!/bin/bash
echo $MONGO_DATABASE
You can pass data to your shell scripts with either environment variables or with parameters. Sometimes one is more convenient, sometimes the other.
See the docs for more info:
Update
You can send more then one argument with spaces to use $1, $2 and $3:
var myscript =
exec('bash ./scripts/mongo-backup.sh ' + dbname + ' ' + dbuser + ' ' + dbpass);
Same as above but with backticks, to use $1, $2 and $3:
var myscript =
exec(`bash ./scripts/mongo-backup.sh ${dbname} ${dbuser} ${dbpass}`);
Same as above but without string concatenation, to use $1, $2 and $3:
var myscript =
spawn('bash', ['./scripts/mongo-backup.sh', dbname, dbuser, dbpass]);
Or passed as environment variables, to use as $dbname $dbuser $dbpass:
var env = Object.assign({}, process.env, { dbname, dbuser, dbpass });
var myscript = spawn('bash', ['./scripts/mongo-backup.sh'], { env });
,+is invalid