3

am trying to execute multiple terminal commands through node script

i have a shell script like smaple.sh and it working fine

cd ~/Desktop
find -type f -printf '%T+\t%p\n' | sort -n

Am trying to execute the above terminal commands in node script

        var command = ' cd ~/Desktop'
        command +=' find -type f -printf %T+\\t%p\\n | sort -n' 

 exec(command, function (error, stdout, stderr) {

});

while executing the above code am getting nothing. first i need to change the directory then execute the second command

find -type f -printf %T+\\t%p\\n | sort -n

1 Answer 1

3

With your current code, node.js is trying to execute the following:

cd ~/Desktop find -type f -printf %T+\\t%p\\n | sort -n

if you try run that outside of node, you'll get the same results.

You need to deliminate the commands using either && or ;, like so:

var command = ' cd ~/Desktop &&'
command +=' find -type f -printf %T+\\t%p\\n | sort -n' 

exec(command, function (error, stdout, stderr) {

});

A perhaps more elegant approach:

var commands = [];
commands.push('cd ~/Desktop');
commands.push('find -type f -printf %T+\\t%p\\n | sort -n');

var command = commands.join(' && ');

exec(command, function (error, stdout, stderr) {

});
Sign up to request clarification or add additional context in comments.

2 Comments

am getting exec error: Error: Command failed: execvp(): No such file or directory But i alreday have that directry
while executing ur code on terminal it is working fine.but using exec am getting the above error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.