1

I have written a small bash script (datalogger.sh) to store the mqtt data on to SD card inside a linux machine. The bash script is as below:-

#!/bin/bash
fileNumber=1
temp=1 // flag to check and create new files
fileName="Data"
while [ $temp -le 1 ]
do
  if [ -f "/media/card/$fileName$fileNumber.txt" ]
  then
    ((fileNumber++))
  else
    touch "/media/card/$fileName$fileNumber.txt"
    mosquitto_sub -v -t "gateway/+/rx" | tee /media/card/$fileName$fileNumber.txt
    temp=2
  fi
done

The bash script works totally fine if i run it with the following command

./datalogger.sh

As of next step, i used the update-rc.d datalogger.sh defaults so that on boot the bash script automatically runs. However, i only get the empty text files. Could anyone guide me, what mistake i am making? Best Regards,

0

2 Answers 2

1

When started from system start-up scripts, processes usually get a quite limited set of environment variables compared to a regular user session.

mosquitto_sub tries to read a configuration file from either $XDG_CONFIG_HOME/mosquitto_sub or $HOME/.config/mosquitto_sub. When started from a startup script, $XDG_CONFIG_HOME is unlikely to be defined, and even $HOME might not exist.

Even the $PATH variable might be different from the normal user's, and so the script might fail to find the mosquitto_sub command.

0

Services generaly use wrapper scripts like for example;

#!/bin/bash

# Provides: example
# Required-Start:
# Should-Start:
# Required-Stop:
# Default-Start: 2 3 5
# Default-Stop: 0 1 2 6
# Short-Description: example
# Description: example

#
# /etc/init.d/example
#

set -e
trap 'echo "ERROR: $BASH_SOURCE:$LINENO $BASH_COMMAND" >&2' ERR

NPID=$(pgrep -f example2.sh || true);

function start {
    if [ "$NPID" = "" ] ; then
        screen -S example -d -m bash -c '/root/example2.sh'
    else
        echo "example service is already running as $NPID";
    fi
}

function stop {
    if [ "$NPID" != "" ] ; then
        kill "$NPID";
    else
        echo "example service was not running" >&2;
    fi
}

function status {
    if [ "$NPID" = "" ]; then
        echo "example is not running";
    else
        echo "example is running with pid $NPID";
    fi
}

if [ "$1" = "start" ]; then
    start
elif [ "$1" = "stop" ]; then
    stop
elif [ "$1" = "restart" ]; then
    stop;
    start;
elif [ "$1" = "status" ]; then
    status
else
    echo " * Usage: /etc/init.d/example {start|status|stop|restart}";
fi
1
  • True, of course, but how does this answer the OP? Are you suggesting they should write something like this? How would that look?
    – terdon
    Commented Apr 4 at 19:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .