EN
Bash - simple URL ping tool (URL response time measuring)
10 points
In this short article, we would like to show how in Bash, write a simple tool that pings indicated URLs checking response time.
test_requests.sh
file:
xxxxxxxxxx
1
2
3
function test_request()
4
{
5
url="$1"
6
7
t1=$(date +%s%9N)
8
9
curl -k "${url}" &> /dev/null
10
11
t2=$(date +%s%9N)
12
dt=$((t2 - t1))
13
14
printf "%16d %16d %16d %16d %s\n" \
15
$dt \
16
$(($dt / 1000)) \
17
$(($dt / 1000000)) \
18
$(($dt / 1000000000)) \
19
"$url";
20
}
21
22
echo
23
echo -n " [in nanoseconds] ";
24
echo -n "[in microseconds] ";
25
echo -n "[in milliseconds] ";
26
echo -n " [in seconds] ";
27
echo -n " [requested url] ";
28
echo
29
30
test_request "https://dirask.com/posts/MySQL-select-last-row-j890a1"
31
test_request "http://localhost/posts/MySQL-select-last-row-j890a1"
32
33
echo
Script running:
xxxxxxxxxx
1
./test_requests.sh
2
3
# or:
4
5
watch -n 1 ./test_requests.sh
Example output:
xxxxxxxxxx
1
Every 1.0s: ./test_requests.sh my-server: Sun May 23 13:00:56 2021
2
3
4
[in nanoseconds] [in microseconds] [in milliseconds] [in seconds] [requested url]
5
110754854 110754 110 0 https://dirask.com/posts/MySQL-select-last-row-j890a1
6
95801101 95801 95 0 http://localhost/posts/MySQL-select-last-row-j890a1
7
In this example, we are able to change Host:
header to the proper domain.
That configuration is useful when we have VirtualHost
s that redirect traffic depending on a specific domain.
test_requests.sh
file:
xxxxxxxxxx
1
2
3
function test_request()
4
{
5
url="$1"
6
host="$2"
7
8
t1=$(date +%s%9N)
9
10
if [ -n "$host" ];
11
then
12
curl -k --header "Host: $host" "$url" &> /dev/null
13
else
14
curl -k "$url" &> /dev/null
15
fi
16
17
t2=$(date +%s%9N)
18
dt=$((t2 - t1))
19
20
printf "%16d %16d %16d %16d %s" \
21
$dt \
22
$(($dt / 1000)) \
23
$(($dt / 1000000)) \
24
$(($dt / 1000000000)) \
25
"$url";
26
27
[ -n "$host" ] && echo -n " (Host: $host)";
28
29
echo
30
}
31
32
echo
33
echo -n " [in nanoseconds] ";
34
echo -n "[in microseconds] ";
35
echo -n "[in milliseconds] ";
36
echo -n " [in seconds] ";
37
echo -n " [requested url] ";
38
echo
39
40
test_request "https://dirask.com/posts/MySQL-select-last-row-j890a1" ""
41
test_request "https://localhost/posts/MySQL-select-last-row-j890a1" "dirask.com"
42
43
echo
Script running:
xxxxxxxxxx
1
./test_requests.sh
2
3
# or:
4
5
watch -n 1 ./test_requests.sh
Example output:
xxxxxxxxxx
1
Every 1.0s: ./test_requests.sh my-server: Sun May 23 13:00:56 2021
2
3
4
[in nanoseconds] [in microseconds] [in milliseconds] [in seconds] [requested url]
5
110754854 110754 110 0 https://dirask.com/posts/MySQL-select-last-row-j890a1
6
95801101 95801 95 0 https://localhost/posts/MySQL-select-last-row-j890a1 (Host: dirask.com)
7