forked from afw-org/afw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
repeat-command.sh
executable file
·70 lines (55 loc) · 1.62 KB
/
repeat-command.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/bin/bash
# This script runs the specified command in a loop and prints the duration of
# each iteration. If the command takes longer than the specified timeout value,
# it is killed and the iteration is counted as a kill.
stop_on_timeout=false
if [ "$1" == "--stop" ]; then
stop_on_timeout=true
shift
fi
command_to_run=$1
timeout_value=${2:-120}
counter=0
kill_counter=0
current_pid=0
# Function to handle script interruption
handle_interrupt() {
echo 'Script interrupted by user'
if [ $current_pid -ne 0 ]; then
kill $current_pid
echo "Killed running command with PID: $current_pid"
fi
exit 0
}
trap handle_interrupt SIGINT
if [ -z "$command_to_run" ]; then
echo "Usage: $0 [--stop] <command> [timeout_in_seconds]"
exit 1
fi
if [ $? -ne 0 ]; then
echo "Failed to change directory to /workspaces/afw. Exiting."
exit 1
fi
while true; do
((counter++))
start_time=$(date +%s%N)
# Use the timeout command to limit the command's execution time to the specified timeout value
timeout $timeout_value $command_to_run &
current_pid=$!
wait $current_pid
exit_status=$?
end_time=$(date +%s%N)
duration=$(echo "($end_time - $start_time) / 1000000000" | bc -l)
duration=$(printf "%.1f" $duration)
if [ $exit_status -eq 124 ]; then
((kill_counter++))
echo "Command killed due to timeout on iteration: $counter"
if $stop_on_timeout; then
echo "Stopping script due to --stop argument and command timeout."
exit 1
fi
fi
current_pid=0
echo "Running '$command_to_run' iteration: $counter, Duration: $duration seconds, Kills: $kill_counter"
sleep 1
done