2

In my node.js script, I need to run these two commands with sudo:

execSync('sudo rsync -a ' + dir1 + " " + dir2);
execSync('sudo rm -Rf ' + dir1);

but this cause that it will ask for sudo password two times; other than this, if I digit a wrong password, the script goes on without requesting it again; how can I cache the password to avoid to be prompted for it two times and wait until the correct password is supplied before going on?

Cereal Killer
  • 3,387
  • 10
  • 48
  • 80
  • 1
    You can login as root and have the permissions (but it's ill-advised). – nonamorando Jan 02 '15 at 23:57
  • Yes this is true but I need to use sudo; – Cereal Killer Jan 02 '15 at 23:59
  • 1
    Well the issue with that is that the whole point of sudo is to give the given user, superuser privileges for one command. Future reference: more background to sudo: http://stackoverflow.com/questions/26960665/whats-the-point-of-permissions-in-linux-if-anyone-can-do-a-sudo – nonamorando Jan 03 '15 at 00:02

1 Answers1

4

Following this piece of advice, I would also advise to just execute both commands under the same sudo command.

execSync('sudo -- sh -c \'rsync -a ' + dir1 + ' ' + dir2 + ' && rm -Rf ' + dir1 + '\'');

Detecting whether an error occurred can be done from execSync itself. It seems that an exception is thrown when stderr is not empty. I would have first suggested to check the command's exit code, but that library does not seem to expose it.

E_net4
  • 27,810
  • 13
  • 101
  • 139