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?
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.