```bash ### BEGIN INIT INFO # Provides: # Required-Start: $remote_fs $syslog # Required-Stop: $remote_fs $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Start daemon at boot time # Description: Enable service provided by daemon. ### END INIT INFO dir="/share/InstalledPrograms/metricbeat" logdir="/share/InstalledPrograms/var/log" cmd="/share/InstalledPrograms/metricbeat/metricbeat --path.data $dir/data --path.config $dir --path.logs $logdir -c $dir/metricbeat.yml run" #user="" name="metricbeat" pid_file="/share/InstalledPrograms/var/run/$name.pid" stdout_log="/share/InstalledPrograms/var/log/$name.log" stderr_log="/share/InstalledPrograms/var/log/$name.err" if [ -f $pid_file ]; then pid="$(cat $pid_file)" fi mb_proc_pid="$(/bin/ps -ef | /bin/grep metricbeat | /bin/grep -v grep | grep -v "$0" | /bin/sed -E 's/((^[^0-9]{0,5}|^[0-9])[0-9]*).*/\1/g' | xargs)" is_running() { if [ -f "$pid_file" ]; then pid="$(cat $pid_file)" proc_count="$(ps | grep $pid | grep -v grep | wc -l)" got_set="y" [ -f "$pid_file" ] && [ "$proc_count" == 1 ] else false fi } #check_proc() { # if [[ "$proc_pid" ]]; then return 1; fi #} do_stop() { if [[ ! "$1" ]]; then echo "$(date --rfc-3339=seconds) No pid supplied to stop function" exit 1 fi if ! is_running; then echo "NOT RUNNING" return 0 fi do_stop_pid="$1" if [[ "$2" ]]; then kill_command="kill -$2 $pid" echo -n "Stopping $name with signal $2.." else kill_command="kill $pid" echo -n "$(date --rfc-3339=seconds) Stopping $name.." fi $kill_command for i in 1 2 3 4 5 6 7 8 9 10; do if ! is_running; then echo '\n' return 0 else sleep 0.3 echo -n "." fi return 1 done } case "$1" in start) if is_running; then echo "ALREADY STARTED" exit 0 elif [[ "$mb_proc_pid" ]] && ! is_running; then echo "$(date --rfc-3339=seconds) Running and missing pid." for mb_pid in $mb_proc_pid; do kill -9 $mb_pid done rm -rf "$dir/data/" #kill -9 $proc_pid exit 1 else cd "$dir" rm -rf "$dir/data/" #ls $dir/data/ if [ -z "$user" ]; then sudo $cmd >>"$stdout_log" 2>>"$stderr_log" & else sudo -u "$user" $cmd >>"$stdout_log" 2>>"$stderr_log" & fi echo $! >"$pid_file" echo $(cat $pid_file) if ! is_running; then echo "FAILED TO START" echo "See $stdout_log and $stderr_log" exit 1 else echo "STARTED" fi fi ;; stop) if is_running; then do_stop $pid if is_running; then do_stop $pid 9 fi if is_running; then echo "FAILED TO STOP" echo "$(date --rfc-3339=seconds) Not stopped; may still be shutting down or shutdown may have failed" exit 1 else echo "STOPPED" if [ -f "$pid_file" ]; then rm "$pid_file" fi fi else echo "NOT RUNNING" fi ;; restart) $0 stop if is_running; then echo "STOP FAILED" exit 1 fi $0 start ;; status) if is_running; then echo "RUNNING" else echo "STOPPED" exit 1 fi ;; *) echo "Usage: $0 {start|stop|restart|status}" exit 1 ;; esac exit 0 ```