Search code examples
linuxbashcentosredhat

Bash timeout command doesn't work within a script


I try do an echo if the systemctl command takes too long, the following works perfectly when executed in terminal, but if I paste the exact same line in a script and execute that script, the echo is always called. When executing the stop command on it's own it takes max 2min normally and I always checked the logs of the service and saw that it stopped well within time. But the timeout keeps going when the command is located within a script.

/usr/bin/timeout 180 /bin/systemctl stop aem-service || echo "test"

My goal with this command is to print test when either /bin/systemctl stop aem-service takes too long (longer than 180 seconds) or it exits with a non-zero exit code

This is tested on a CentOS 7 virtual machine.

[EDIT] When only executing /usr/bin/timeout 180 /bin/systemctl stop aem-service I get as exit code 124, which indicates a timeout. /bin/systemctl stop aem-service on it's own results in exit code 0


Solution

  • I found the solution: systemctl seemed to be waiting for 'input' for authentication when ran from a script. It didn't really need this, so it immediately succeeded when not ran from a script. I solved the problem by adding --no-ask-password:

    /usr/bin/timeout 180 /bin/systemctl --no-ask-password stop aem-service || echo "test"