Score:1

Why echo text won't work within systemd service

vn flag

This bash script worked fine alone:

#!/bin/bash
OtherIP=172.17.1.2
while [ true ]
do
  echo "cannot connect to $OtherIP" >>pgha.log
  sleep 2s
  psql -h $OtherIP -U checker -c '\l' template1 &>/dev/null

  if [ $? -eq 0 ]; then
        echo `date` 'Finally,' >>pgha.log
        echo 'pgpool is available on host='$OtherIP  >>pgha.log
        break
  fi
done

Basically, as I start postgresql on the server 172.17.1.2 this script would jump out of the loop and write the last words "pgpool is available on host=172.17.1.2". But as I put this script in systemd service it no longer output to pgha.log, here is auto_pgha.service:

[Unit]
Description=run pgpool after auto_pgha service ## <-change run_XXX.sh

[Service]
Type=oneshot
ExecStart=/root/test1.sh ## <-change run_XXX.sh

[Install]
WantedBy=multi-user.target

Fair enough, I have also checked systemctl status auto_pgha after enabling it and reboot the server while 172.17.1.2 server did not run postgresql, it says activating

● auto_pgha.service - run pgpool after auto_pgha service ## <-change run_XXX.sh
     Loaded: loaded (/usr/lib/systemd/system/auto_pgha.service; enabled; vendor preset: disabled)
     Active: activating (start) since Fri 2023-06-30 15:30:51 CST; 35s ago
   Main PID: 563 (test1.sh)
      Tasks: 2 (limit: 4656)
     Memory: 1.9M
        CPU: 74ms
     CGroup: /system.slice/auto_pgha.service
             ├─ 563 /bin/bash /root/test1.sh ## "<-change" run_XXX.sh
             └─3833 sleep 2s

After starting postgresql on 172.17.1.2, it is dead as expected but still nothing in pgha.log - in fact, no file pgha.log at all since I deleted it before reboot. How can I fix this error?

Score:0
sm flag

IMO your code looks good, except for a detail.

It won't work:

echo "cannot connect to $OtherIP" >>pgha.log

It is expected to work:

echo "cannot connect to $OtherIP" >> pgha.log
George Y avatar
vn flag
Thanks for reply. But I found `pgha.log` in `/`, `WorkingDirectory=/root` would fix this issue.
user1686 avatar
fr flag
This is not right in general; pretty much _all_ shells parse and accept `>file` in the same way as `> file` (and likewise for all other redirect operators).
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.