crontab bash tests

Ralf Mardorf kde.lists at yahoo.com
Tue Sep 26 11:32:29 UTC 2023


On Tue, 2023-09-26 at 20:07 +1000, Karl Auer wrote:
> Simplifying the pipeline, simplifying the conditionals, simplifying the
> tests, removing bashisms and putting the commands into a  script have
> all been suggested to the OP already. None were adopted, apparently an
> unreadable, overly complex, bashism-containing in-cron command line is
> preferred.

Hi,

I didn't read the whole thread. So even for troubleshooting purpose
checking the exit statuses wasn't done step by step?

First I would ensure that stdout of /usr/bin/psql is always the same,
when running it from command line or running it by cron, so I would
replace it with e.g. echo.

Troubleshooting could look similar to this:

   • rocketmouse at archlinux ~ 
   $ [[ $(echo "streaming" | grep streaming > /dev/null)$? -eq 0 ]]; echo $? >> Desktop/log.txt
   • rocketmouse at archlinux ~ 
   $ [[ $(echo "gnimaerts" | grep streaming > /dev/null)$? -eq 0 ]]; echo $? >> Desktop/log.txt
   • rocketmouse at archlinux ~ 
   $ echo "# # # #" >> Desktop/log.txt 
   • rocketmouse at archlinux ~ 
   $ [[ $(echo "streaming" | grep streaming > /dev/null)$? -eq 0 ]] && echo "&& $?" >> Desktop/log.txt || echo "|| $?" >> Desktop/log.txt
   • rocketmouse at archlinux ~ 
   $ [[ $(echo "gnimaerts" | grep streaming > /dev/null)$? -eq 0 ]] && echo "&& $?" >> Desktop/log.txt || echo "|| $?" >> Desktop/log.txt
   • rocketmouse at archlinux ~ 
   $ cat Desktop/log.txt 
   0
   1
   # # # #
   && 0
   || 1

IMO already a test line like

   [[ $(echo "streaming" | grep streaming > /dev/null)$? -eq 0 ]] && echo "&& $?" >> Desktop/log.txt || echo "|| $?" >> Desktop/log.txt

isn't human readable anymore. I would use a script and perhaps instead of "if else" use "case in".

similar to

   #!/bin/a_sh_that_fits_my_needs
   
   sudo -u postgres psql --quiet --port=5433 -x -c 'select state from pg_stat_replication;' | grep streaming > /dev/null
   
   case $? in
     0) touch /tmp/foo;;
     *) rm /tmp/foo;;
   esac
   
   exit

With log file:

   #!/bin/a_sh_that_fits_my_needs
   
   sudo -u postgres psql --quiet --port=5433 -x -c 'select state from pg_stat_replication;' | grep streaming > /dev/null
   
   exit_status=$?
   
   echo "grep  exit status: $exit_status" > log.txt
   
   case $exit_status in
     0) echo "touch exit status: $?" >> log.txt
        touch /tmp/foo
        ;;
     *) echo "rm    exit status: $?" >> log.txt
        rm /tmp/foo
        ;;
   esac
   
   exit

Regards,
Ralf



More information about the ubuntu-users mailing list