Running a jar package in Linux typically involves using java -jar xx.jar
, which can be quite inconvenient. Therefore, I created a shell script to manage the starting, stopping, and restarting of the jar package.
The shell script is designed to implement four main functions: start, stop, restart, and check the status.
Here is the script code:
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
71
72
73
74
75
76
77
78
79
80
81
82
83
|
#!/bin/bash
#
# A shell script for managing a jar with start, restart, and stop functionality
#
# JVM parameters
jvm_xms=-Xms512m
jvm_xmx=-Xmx512m
# Jar name
jar_name=app.jar
# Jar directory
jar_dir=/root/test
# Process ID
pid=
# Start function
start() {
# Get the process ID
getpid
# If the process ID exists and the corresponding directory also exists
if [ "$pid" != "" ] && [ -d /proc/$pid ]; then
echo "$jar_name is already running, process ID is $pid"
else
echo "Starting: $jar_name"
nohup java -server $jvm_xms $jvm_xmx -jar $jar_dir/$jar_name > /dev/null 2>&1 &
fi
}
# Stop function
stop() {
# Get the process ID
getpid
# If the process ID exists and the corresponding directory also exists
if [ "$pid" != "" ] && [ -d /proc/$pid ]; then
# Kill the process ID
kill -KILL $pid >/dev/null 2>&1
# Sleep for 10 seconds
usleep 100000
echo "$jar_name has been stopped"
else
echo "$jar_name is not running"
fi
}
# Restart function
restart() {
stop
start
}
# Function to get the process ID
getpid() {
pid=`ps -ef | grep "$jar_dir/$jar_name" | grep -v grep | awk '{print $2}'`
}
# Execution parameters
case "$1" in
start)
echo "------------------------ Executing Start ------------------------"
start
;;
stop)
echo "------------------------ Executing Stop ------------------------"
stop
;;
restart)
echo "------------------------ Executing Restart ------------------------"
restart
;;
status)
echo "------------------------ Checking Status ------------------------"
getpid
if [ "$pid" != "" ] && [ -d /proc/$pid ]; then
echo "$jar_name is running, process ID is $pid"
else
echo "$jar_name has been stopped"
fi
;;
*)
echo "Usage: $0 {start|stop|restart|status}"
;;
esac
|
Save the above script as xxxx.sh
and grant execute permissions with chmod +x /root/xxxx.sh
.
Finally, run the script to test it.
