Kingalione Kingalione - 1 year ago 65
Bash Question

nodejs exec giving other output than function call in real terminal

I have the problem that when I run a terminal command in nodejs via child_process.exec I get another output than when I run the command in a real terminal.

My code looks like this:

function checkLocalIP() {
logger.debug("Checking the local IP");

execute("ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v ''", function(localIP) {
if(isIp.v4(localIP)) {
logger.debug("Local IP found",{localIP:localIP});
return true;
} else {
logger.error("Local IP not found",{localIP:localIP});
return false;

function execute(command, callback){
logger.debug("Executing command: "+command,{command:command});
exec(command, function(error, stdout, stderr){

If I run this command in a real terminal I get only the IP like this:

$ ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v ''

But in nodejs I get this string as stdout:

"ine\nt 127.0\n.0.1\nine\nt 192.168\n.178.222"

I'm wondering why the outputs are not similar and why the nodejs call also outputs me the IP because it is excluded in the command.

Answer Source

Remember to escape \. Remember that in js, like in C or similar languages, \ has a special meaning in strings:

So your string:

"ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v ''"

is interpreted as:

ifconfig | grep -Eo 'inet (addr:)?([0-9]*.){3}[0-9]*' | grep -Eo '([0-9]*.){3}[0-9]*' | grep -v ''

Note the missing \. This obviously leads to a wrong regex being used.

To fix it, escape your \:

"ifconfig | grep -Eo 'inet (addr:)?([0-9]*\\.){3}[0-9]*' | grep -Eo '([0-9]*\\.){3}[0-9]*' | grep -v ''"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download