I'm trying to spawn a process from nodejs, with spawn from child_process. But the command I'm trying to run is an alias inside the .bashrc file of the running user.
// index.ts or whatever
import { spawn } from "child_process";
spawn('cmdAlias', [args], {
env: process.env,
stdio: 'inherit',
shell: '/bin/bash'
});
// .bashrc
[...]
alias cmdAlias='echo foo'
This doesn't work, it throws a command not found (cmdAlias).
If I try to reconfigure bash manually by running:
// index.ts or whatever
import { spawn } from "child_process";
spawn('source $HOME/.bashrc; cmdAlias', [args], {
env: process.env,
stdio: 'inherit',
shell: '/bin/bash'
});
Then I get source command not found!
There a way to spawn a process with the aliases loaded?
(note the alias works from terminal, that's a given)
PS: oversimplified examples here
I tried these steps on my OS and it worked:
nano ~/.bashrc
alias cmdAlias='echo foo'
to .bashrc
// ./cmdAliasWrapper
#!/bin/bash
echo "Running cmdAliasWrapper.sh"
bash -i -c "cmdAlias $*"
exit 1
// ./test.js
const spawn = require('child_process').spawn;
const args = [
"echo 'This ran from test.js'"
];
spawn('./cmdAliasWrapper.sh', args, {
env: process.env,
stdio: 'inherit',
shell: '/bin/bash'
});
chmod +x ./cmdAliasWrapper.sh
node ./test.js
Now you should see this on your console:
Running cmdAliasWrapper.sh
echo foo This ran from test.js
Edit: We can do the same operation without a .sh file:
// ./test.js
const spawn = require('child_process').spawn;
const args = [
"-i",
"-c",
"cmdAlias 'This ran from test.js'"
];
spawn('bash', args, {
env: process.env,
stdio: 'inherit',
shell: '/bin/bash'
});