DOCTL While Loop Not Working in CRON

Posted January 12, 2020 1.4k views

When I run the following manually via the command line, it work beautifully.

However, when I run this same script via sudo crontab, it just deletes everything. What could I be doing wrong:

Assumption: There are 10 snapshots for this specific droplet.



SNAPSHOTS=$(sudo /snap/bin/doctl compute image list-user --format "ID,Type" --no-header | grep snapshot | wc -l)

# Deleting all snapshots beyond $NUMRETAIN
while [[ "$SNAPSHOTS" -gt "$NUMRETAIN" ]]
        OLDEST=$(sudo /snap/bin/doctl compute image list-user --format "ID,Type" --no-header | grep -e '$DROPLETID\|snapshot' | awk '{print$1}' | head -n 1)
        OLDESTNAME=$(sudo /snap/bin/doctl compute snapshot list --format "ID,Name,ResourceId" | grep $DROPLETID | awk '{print$2}' | head -n 1)
        echo "Deleting "$OLDESTNAME""
        sudo /snap/bin/doctl compute image delete $OLDEST --force 
        SNAPSHOTS=$(sudo /snap/bin/doctl compute snapshot list --format "ID,Name,ResourceId" --no-header | grep $DROPLETID | awk '{print$1}' | wc -l)

sudo crontab -e:

50 12 * * *  /bin/bash /home/aaron/projects/DOCTL-Remote-Snapshot/auto_snapshot.bash

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Submit an Answer
1 answer


Have you allowed the sudo /snap/bin/doctl command to be executed without a password? You could do that by editing your sudoers file with the visudo command and adding something like:

your_user host = (root) NOPASSWD: /snap/bin/doctl

Otherwise, the script looks absolutely correct. Besieds that I have 2 other suggestions, enable debug by adding set -x after the #!/bin/bash, and also try to output the STDOUT and STRERR to a log file so that you could check the output for any errors and strange values:

50 12 * * *  /bin/bash /home/aaron/projects/DOCTL-Remote-Snapshot/auto_snapshot.bash > /path/to/log.txt 2>&1

Hope that this helps!