Simulate a bash script crash

I am trying to test a bash script that restarts a child process when the child process crashed.
How can I make a crash bash script?

(I am trying to test a script that restarts the process)

+4
source share
3 answers

To exit the script during the error message, use:

exit 1

This exits with an exit code 1, indicating a failure. Other non-zero numbers may be used to signal various failure conditions. exit 0signals success.

To throw an exception, use kill. To give a hang signal, for example, from a script, run:

kill -SIGHUP $$

, , :

kill -l
+6

- ?

# this simulates a script returning exit code of 1
sh -c 'exit 1'
+4

@ John1024, , :

worker: script, ( ) , :

#!/usr/bin/env bash

n=${1:-2}  # Default to 2 seconds

echo "worker: Will self-destruct in $n seconds..."

sleep $n

echo "worker: Self-destructing..."
kill $$

monitor: a script, worker , , , :

#!/usr/bin/env bash

workerScript='./worker'

# Loop that ensures that the worker script
# is launched and restarted after it terminates.
while true; do

  echo "monitor: Launching worker script in background..."
  "$workerScript" &

  # Wait for the worker script to terminate,
  # for whatever reason, and record its exit code.
  echo "monitor: Waiting for worker script to terminate..."
  # ${!} ($!) is the PID of the most recently started background command.
  # `wait` reports the specified process' exit code.
  wait ${!}; ec=$?  

  # Report worker exit code and restart.
  echo "monitor: Worker script terminated with exit code $ec; restarting..."

done

:

  • kill [SIG]TERM, 15 (. kill -l).

  • bash , , 128 + <signal number>.

  • , kill , -TERM 143; -HUP (-SIGHUP), 129.

+2
source

Source: https://habr.com/ru/post/1538929/


All Articles